1

I have a jQuery function that when a certain button is clicked it removes certain html. This HTML does not exist in the DOM until another button is clicked. The button that when clicked removes the HTML does not exist until the other button is clicked and when clicked it removes itself. Is there a problem with this being in the $('document').ready() function? If not where should it be.

Why I ask is because I know I have caused a bug somehow with this function but cannot figure out where. If you have any other ideas it would be very helpful.

Heres the code:

<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
})

The full code is here if this would help: http://jsfiddle.net/chromedude/ggJ4d/

4

3 回答 3

2

在运行时使用实时而不是点击

Live 将用于将来参考 dom 元素。

$('#saveBttn').live('click', function() {

});
于 2010-11-24T03:52:29.740 回答
2

您的问题来自这样一个事实,即input当文档准备好时,您绑定点击处理程序的 html 元素不存在。.click()这意味着当您的处理程序被实例化时它不存在。要将处理程序绑定到现在和将来存在的元素,您可以使用.live().delegate()。我更喜欢后者,因为它不会绑定到document并等待事件冒泡,而是绑定到您传递给它的选择器,并且只监视在该特定元素内触发的冒泡事件。

因此,考虑到这一点,您可以像这样修改您的代码:

$('#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
});
于 2010-11-24T04:01:20.157 回答
0

您可能应该将代码放在.click()生成 HTML 的按钮中。

顺便说一句,您需要关闭input标签,例如:

<input type="text" id="testSubj"/>

代替:

<input type="text" id="testSubj">

根据您的 jsfiddle (http://jsfiddle.net/chromedude/ggJ4d/),这样的事情应该可以工作:

$('#new').click( function() {//if a new test is wanted to be created...
    $('#popups').append($formHtml);

    $('#saveBttn').click( function() {//if the save button on the create test form is clicked...
        $('#createform').empty();//gets rid of the create test form
    })
})
于 2010-11-24T03:53:01.233 回答