我有一個帶有類名的復選框anotherCheese,當有人點擊它時,它將附加到steps-row-first類,附加的還有一個帶有類名的單選按鈕anotherCheese,但我的點擊事件沒有被呼叫在帶有類名的新單選按鈕上anotherCheese,我做錯了什么?
這是HTML
<div class="steps-row-first">
<div class="radio-wrapper">
<div class="radio-group">
<input type="radio" class="anotherCheese" name="anotherCheese" value="yes" />
<label>Yes</label>
</div>
<div class="radio-group">
<input type="radio" name="anotherCheese" value="no" />
<label>No</label>
</div>
</div>
</div>
和 jQuery:
$('.anotherCheese').on("click", function(){
if($(this).val() == 'yes')
{
$(".steps-row-first").append('<div > <div > <input type="radio" name="anotherCheese" value="yes"/> <label>Yes</label> </div><div > <input type="radio" name="anotherCheese" value="no"/> <label>No</label> </div></div>');
}
});
uj5u.com熱心網友回復:
將事件系結到祖先元素,如.step-row-first. 下面的示例有一些更改,但本質上,通過系結到祖先元素,您可以利用事件冒泡并控制子元素的所有行為——這稱為事件委托。
在以下示例中:
.step-row-first是一個<form>- “點擊”事件現在是“更改”事件。
- 注意第二個引數是:
".anotherCheese",將其指定為this。 <div>改為<fieldset>for語意。
順便說一句,由于您沒有使用任何#ids (不錯的選擇),因此您可以使用.clone()您只需在附加之前取消選中克隆即可。
$(".steps-row-first").on("change", ".anotherCheese", function() {
if ($(this).val() == 'yes') {
$(".steps-row-first").append(`
<fieldset >
<fieldset >
<input type="radio" name="anotherCheese" value="yes" />
<label>Yes</label><br>
<input type="radio" name="anotherCheese" value="no" />
<label>No</label>
</fieldset>
</fieldset>`);
}
});
<body>
<form class="steps-row-first">
<fieldset class="radio-wrapper">
<fieldset class="radio-group">
<input type="radio" class="anotherCheese" name="anotherCheese" value="yes" />
<label>Yes</label><br>
<input type="radio" name="anotherCheese" value="no" />
<label>No</label>
</fieldset>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
/* Make sure that all of the <script> tags are right before the closing </body> tag */
</script>
</body>
uj5u.com熱心網友回復:
你不是從 a'開始的,而是從‘jquery 固定代碼開始的
$('.anotherCheese').on("click", function(){
if($(this).val() == 'yes')
{
$(".steps-row-first").append('<div >
<div > <input type="radio"
name="anotherCheese" value="yes"/>
<label>Yes</label> </div><div > <input
type="radio" name="anotherCheese" value="no"/>
<label>No</label> </div></div>');
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/439714.html
標籤:javascript jQuery
