简体   繁体   English

如何使 JavaScript 中添加的元素与 HTML 中添加的元素反应相同?

[英]How to make elements added in JavaScript react the same as added in HTML?

I am trying to add new elements in JavaScript, and when I hover my mouse over them I want to see how many letters are in the innerHTML.我正在尝试在 JavaScript 中添加新元素,当我将鼠标放在 hover 上时,我想查看 innerHTML 中有多少个字母。 The function works on elements added in html, but the new ones not. function 适用于 html 中添加的元素,但新元素不适用。

 var input = document.getElementById("input") var button = document.getElementById("button"); button.onclick = function () { var p = document.createElement("p"); p.innerHTML = input.value; document.body.appendChild(p); p.id="p"; } var ar = document.getElementsByTagName("p"); for (var i = 0; i < ar.length; ++i) { ar[i].title=ar[i].innerHTML.length; }
 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> </head> <body> <input id="input"></input> <button type="button" id="button"> click</button> <p>p1</p> <p>p2</p> </body> </html>

What I want to achive: number of letters of element I hover on,我想要达到的目标:元素 I hover on 的字母数,

What I get: number of letters of elements I hover on, but only these that were added in html.我得到的是:我在 hover 上的元素的字母数,但只有在 html 中添加的那些。

That happens because you are adding title only on page load.发生这种情况是因为您仅在页面加载时添加标题。 And titles are not added when new elements are created.创建新元素时不会添加标题。 You should do something like that on button click:您应该在单击按钮时执行类似的操作:

button.onclick = function () { 
   var p = document.createElement("p");
   p.innerHTML = input.value ;  
   document.body.appendChild(p);
   p.id="p";
   p.title = input.value.length;
}

You could change your click handler like this:您可以像这样更改您的点击处理程序:

button.onclick = function () { 
    var p = document.createElement("p");
    p.innerHTML = input.value ;  
    document.body.appendChild(p);
    p.id="p";
    p.title = input.value.length
}

it would be better to make a new function though, which will perform this code so that you have less code duplication, ie I'd rewrite it like this:不过,最好制作一个新的 function ,它将执行此代码,以便您减少代码重复,即我会像这样重写它:

function applyFormatting(pElement) {
    pElement.title = pElement.innerHTML.length
}

button.onclick = function () { 
    var p = document.createElement("p");
    p.innerHTML = input.value ;  
    document.body.appendChild(p);
    p.id="p";
    applyFormatting(p);
}

var ar = document.getElementsByTagName("p"); 

for (var i = 0; i < ar.length; ++i) {
    applyFormatting(ar[i]);
}

that way the "formatting" you want to apply to your already existing p elements is centralized in a function and you know that the elements will undergo the exact same transformation.这样,您要应用于现有 p 元素的“格式”集中在 function 中,并且您知道这些元素将经历完全相同的转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM