jquery - After adding elements to a div with javascript, an untouched existing link stops working?

问题描述:

I have some html like this

<div id='myArea'></div>

<div id='aDifferentUnrelatedArea'></div>

<a href='#' id='closeButton' class='myButton'>Close</a>

the button has a listener like this

$('#closeButton').click(function(event){

event.preventDefault();

var myNode = document.getElementById("myArea");

while (myNode.firstChild) {

myNode.removeChild(myNode.firstChild);

}

});

and I add elements to myArea like this

document.getElementById('myArea').innerHTML = 'a title';

var newElement = document.createElement('a');

newElement.setAttribute('href', "#");

newElement.appendChild(document.createTextNode('a string'));

document.getElementById('myArea').appendChild(newElement);

Before I add elements, the Close button looks fine. There's nothing to close, but my hover css is applied to it and my cursor becomes the clickable one. After I add elements to myArea like this, the button acts more like a picture and there is no click related to it (it doesn't act like an <a> tag anymore nor does it do the click event).

网友答案:

Sorry for the confusion but thanks for helping me find the problem. The actual problem was I had this floating footer button at the bottom of the page. It seemed to take up the whole line's functionalities (I mean anything on the same line as the button would behave like a picture). I just added extra space at the bottom of the body so nothing would be on the same line as the footer.