我有一个类似类名anotherCheese的复选框,当有人单击它将被附加到steps行-头等舱时,所附加的还有一个带有类名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 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>');
}
});发布于 2022-03-07 20:14:36
将事件绑定到像.step-row-first这样的祖先元素。下面的示例有一些更改,但本质上,通过绑定到一个祖先元素,您可以利用事件冒泡并控制子元素的所有行为--这称为事件委托。
在以下示例中:
.step-row-first是<form>".anotherCheese",它将它指定为this。<div>改为<fieldset> for 语义学。顺便说一句,由于您没有使用任何#id(很好的选择),您可以使用.clone(),您只需在追加克隆之前不检查它。
$(".steps-row-first").on("change", ".anotherCheese", function() {
if ($(this).val() == 'yes') {
$(".steps-row-first").append(`
<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>`);
}
});<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>
发布于 2022-03-07 19:01:09
您不是从'开始,而是从jquery固定代码中的‘开始
$('.anotherCheese').on("click", function(){
if($(this).val() == 'yes')
{
$(".steps-row-first").append('<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>');
}
});https://stackoverflow.com/questions/71385914
复制相似问题