My final solution
$('#2').replaceWith(function(){
return $('<a id="' + $(this).attr('id') + '" href="#" />').append($(this).contents());
});
$('#2').click(function() {
$('#3').toggle();
scrollToDiv($(this),0);
return false;
});
题
I have the html
<div id=1>
<span id=2></span>
</div>
<div id=3>
</div>
I'm trying to replace span
with a
and use the anchor to .toggle()
<div id=3>
$('#2').replaceWith(function(){
return $("<a id=\"2\" href=\"#\" />").append($(this).contents());
});
This works at turning the span to an anchor, but when I try to chain a click function .toggle()
, it refuses to toggle.
$('#2').replaceWith(function() {
return $("<a id=\"2\" href=\"#\" />").append($(this).contents());
}).click(function() {
$('#3').toggle();
return false;
});
The click function .toggle()
works if I remove .replaceWith()
.
解决方案 2
My final solution
$('#2').replaceWith(function(){
return $('<a id="' + $(this).attr('id') + '" href="#" />').append($(this).contents());
});
$('#2').click(function() {
$('#3').toggle();
scrollToDiv($(this),0);
return false;
});
其他提示
You are binding to the element you just removed.
$('#2') // <-- here you already selected the span
// now you replaced it with a new element
.replaceWith(function() {
return $("<a id=\"2\" href=\"#\" />").append($(this).contents());
})
// the selector is still on the span so you bound the click event to the span
.click(function() {
$('#3').toggle();
return false;
});
What you can do is use delegation so it doesn't matter what changes you make to the element. Bind it to a parent element
$('#1').on('click','#2',function(){
//your code here
});
Now your parent element will listen to the click events that bubble up and handle them.. So it doesn't matter how many times you change the #2 element - as long as it's id=2 then it will trigger the handler