I wrote a function that, on clicking a certain element, wo开发者_StackOverflow社区uld replace a div with a hidden span. When I had the event handler in the "onclick=" attr in the tag, the function worked fine. But then I tried to get "fancy" and replace onclick attr with jQuery's .click() method. Now, when I try to use it on the page, nothing but a clunk -- nothing happens.
However, if I execute the exact same code in Chrome's js console, it works great. Here is my js:
$("a#delete").click(function () {
$("a#delete").replaceWith($("span.hconf").attr("style", "none"))
});
Here is the relevant html (the is inside a div, the is outside):
<a class='modify' id="delete" u="{{ i.id }}" href='#'>delete</a>
<span class='hconf' style="display:none;">Are you sure? <a class='confirm' id='del_conf_true' onclick='deltrue();' href='#'>yes</a> | <a class='confirm' id='del_conf_false' href='#'>no</a></span>
I know I can change the second $("a#delete") with the "this" keyword, but I am leaving that undone now as I'm not sure if that's part of the problem. I am a newcomer to js/jQuery.
Ready it:
$(document).ready(function() {
$("a#delete").click(function () {
$(this).replaceWith($("span.hconf").attr("style", "display:none"));
});
});
...and don't you mean style="display:none"? You can just as easily use .hide()
:
$("span.hconf").hide();
And lastly, it is pointless using a filtering tag on an ID selector. Just do $("#delete")
, it is both shorter and quicker.
Your code is running before the "delete" anchor HTML is seen by the browser. Thus your jQuery selector "a#delete" finds nothing, and so overall nothing happens. By putting your initialization code in a "ready" handler:
$(function() {
$('a#delete').click(function() { /* ... */ });
});
you defer its execution to a point at which the whole document has been parsed. Alternatively, you could put your script block at the end of the <body>
.
This JS is being ran before the DOM is ready, try putting this code inside a $(function(){})
(DOM ready) block.
$(function(){
$("a#delete").click(function () {
$("a#delete").replaceWith($("span.hconf").attr("style", "display:none"));
});
});
Or, you can try to use .live
.
$("a#delete").live('click', function () {
$("a#delete").replaceWith($("span.hconf").attr("style", "display:none"));
});
NOTE: Use .hide()
and .show()
to change the display attribute.
精彩评论