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

Use live instead of click as you are do that at runtime

Live will be used for future reference dom elements.

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

});
于 2010-11-24T03:52:29.740 に答える
2

Your problem comes from the fact that the html input element you are binding a click handler to does not exist when the document is ready. This means it doesn't exist when your .click() handler is instantiated. To bind handlers to elements that exist now and in the future, you can use .live() or .delegate(). I prefer the latter, because it doesn't bind to document and wait for events to bubble up, instead it binds to the selector you pass it, and only watches for bubbling events that get triggered within that specific element.

So with this in mind, you can revise your code like so:

$('#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

You should probably put the code in the .click() of the button that generates the HTML.

Btw, you need to close the input tags, e.g.:

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

instead of:

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

Based on your jsfiddle (http://jsfiddle.net/chromedude/ggJ4d/), something like this should work:

$('#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 に答える