innerHTML replace pattern not work
I saw a lot of posts about this pattern, but still don't understand why it's not work in mine code. Using Chromium on Ubuntu 10.04.
function showDescription(){
var description = document.createElement('div'),
eventTarget = window.event.target,
newHTML = description.innerHTML;
description.id = 'description';
switch(eventTarget.getAttribute('data-par')){
case 'links': newHTML = newHTML.replace(newHTML, 'links')
break;
case 'images': newHTML = newHTML.replace(newHTML, 'images')
break;
};
console.log(newHTML);
parentElement.insertBefore(description, parentElement.firstChild.nextSibling);
};
var descParLi = descPars.getElementsByTagName('li');
for (var i = 0; i < descParLi.length; i++){
descParLi[i].addEventListener("click", showDescription);
};
This code contained in other fu开发者_JS百科nction. Strangely, in console I see value of newHTML, but in html have no changes, that's a problem. What is wrong? How to fix?
You aren't adding the content to the actual div
you created.
switch(eventTarget.getAttribute('data-par')){
case 'links': description.innerHTML = 'links'
break;
case 'images': description.innerHTML = 'images'
break;
};
console.log( description.innerHTML );
There's no point in doing:
newHTML = description.innerHTML
...or:
newHTML.replace(newHTML, 'images')
...because description
is a brand new element, so there isn't any innerHTML content yet.
EDIT: I used div
instead of description
for the variable name above. It should use description
instead:
description.innerHTML = 'xxxxx'
Fixed.
Here's the entire function:
var i = 0;
function showDescription(){
var description = document.createElement('div'),
eventTarget = window.event.target;
description.id = 'description' + i; // <-- make the ID unique
i++; // <-- increment "i" so that it's different on the next run
switch(eventTarget.getAttribute('data-par')){
case 'links': description.innerHTML = 'links'
break;
case 'images': description.innerHTML = 'images'
break;
};
console.log( description.innerHTML );
// v----What is parentElement supposed to reference?
parentElement.insertBefore(description, parentElement.firstChild.nextSibling);
}
Notice I added an incrementing i
so that your ID will be unique each time.
This won't be necessary if you're removing the element before another one is shown.
Also, you have a parentElement
. I don't know what that's supposed to reference.
If it is some appropriate variable not shown, then you're fine, but if it should be a reference to the parent of the target
, then you should do this instead:
target.parentNode.insertBefore(description, target.parentNode.firstChild.nextSibling);
It seems you haven't actually made newHTML the value of innerHTML, like so:
description.innerHTML = newHTML;
精彩评论