javascript点击函数不;不适用于ID和Class
javascript click function doesn't work for ID and Class?
即使有两段相同的代码,我也无法使jquery函数工作。
这是主要的jquery函数(我删除了"<")。
$(".spoiler").append("<button> Reveal Spoiler!</button>");
$(".spoiler button").click(function() {
$(this).remove();
});
这将创建一个按钮,然后在单击该按钮时将其删除。
现在,当我这样做时:
$("#family-question").click(function(){
$("#answer-one").append("<button> Answer One </button>");
$("#answer-two").append("<button> Answer Two </button>");
$(".test").append("<button> Answer Three </button>");
});
$(".test button").click(function() {
$(this).remove();
});
这将创建所有按钮。但是,如果我点击按钮,它不会被删除。
就HTML代码而言。第一个是;
<p class="spoiler">
<!--Spoiler:-->
<span>Darth Vader is Luke Skywalker's Father! Noooooooooooo!</span>
</p>
第二个有一个ID和一个类;
<p class="test" id="answerswer-one">
<span>Answer Option one</span>
</p>
为什么它不起作用?
.test button
元素在您附加它之前是不存在的。相反,您应该在添加按钮后添加点击事件:
$("#family-question").click(function(){
$("#answer-one").append("<button> Answer One </button>");
$("#answer-two").append("<button> Answer Two </button>");
$(".test").append("<button> Answer Three </button>");
$(".test button").click(function() { // button exists now!
$(this).remove();
});
});
编辑:
一个更好的方法是使用授权。这意味着,当单击指定的元素时,单击事件将查看绑定元素中是否有"button"子元素,并将单击事件传递给button
元素:
$(".test").on('click', 'button', function () {
$(this).remove();
});
这样做的好处是,您只需要绑定一次事件,而且button
甚至不必存在。
相关文章:
- JQueryhide()不适用于Mozzilla,但适用于Chrome
- PHP中的setcookie仅适用于localhost
- html5 drawImage适用于firefox,而不是chrome
- 提供“;onClick"适用于iPad(触摸屏)和桌面用户的默认功能
- jQuery表单验证适用于Mozilla和Internet Explorer,但不适用于Chrome或Safari
- ResolveUrl是否适用于././也
- Firebase updateChildValues适用于IOS,但不适用于Web和Android
- javascript点击函数不;不适用于ID和Class
- JavaScript警报适用于int,但不适用于string
- SQLite插件适用于Mac和Windows,但不适用于手机上的Safari
- Regex Replace仅适用于Last Match
- 如何编写用于id验证的正则表达式(JavaScript)
- window.onload适用于aspx页面,但不适用于普通html
- Jquery Ajax POST不工作.适用于GET
- .load()适用于window,而不是ID
- 使用Jquery更改css样式适用于id's、 不在课堂上
- 面具适用于 ID,但不适用于类
- 为什么不't document.getElementById(id).contentWindow适用于Chrom
- JS won't适用于second 'id'If first 'id'是在另一页
- jQuery .change只适用于ID,而不是当我尝试类