我有一个 jQuery 函数,当单击某个按钮时,它会删除某些 html。在单击另一个按钮之前,此 HTML 不存在于 DOM 中。单击时删除 HTML 的按钮在单击另一个按钮之前不存在,单击时它会自行删除。这在 $('document').ready() 函数中有问题吗?如果不是应该在哪里。
我问的原因是因为我知道我用这个函数以某种方式导致了一个错误,但不知道在哪里。如果您有任何其他想法,那将非常有帮助。
代码如下:
<div id="popups">
<div id="createform">
<div id="createformInside">
<input type="text" id="testTitle" size="20">
<input type="text" id="testSubj">
<span id="testOptions">More Options</span>
<br/>
<textarea id="testContent" ></textarea>
<input type="button" value="Save Test" id="saveBttn">
</div>
</div>
</div>
$('#saveBttn').click( function() {//if the save button on the create test form is clicked...
$('#createform').remove();//gets rid of the create test form
})
如果有帮助,完整代码在这里:http://jsfiddle.net/chromedude/ggJ4d/
最佳答案
您的问题来自这样一个事实,即当文档准备好时,您绑定(bind)点击处理程序的 html input
元素不存在。这意味着当您的 .click()
处理程序被实例化时它不存在。要将处理程序绑定(bind)到现在和将来存在的元素,您可以使用 .live()
或 .delegate()
。我更喜欢后者,因为它不绑定(bind)到 document
并等待事件冒泡,而是绑定(bind)到您传递给它的选择器,并且只监视在特定范围内触发的冒泡事件元素。
考虑到这一点,您可以像这样修改代码:
$('#popups').delegate("#saveBttn", "click", function() {//if the save button on the create test form is clicked...
$('#createform').remove();//gets rid of the create test form
});
关于javascript - 如果我将 jQuery 放置在将某些 HTML 注入(inject) DOM 到 $ ('document' ).ready() 中时将被使用,这是一个问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4263274/