简体   繁体   中英

Why onlick function return this?

let classMessage = document.createElement('class');
document.getElementById("chat").prepend(classMessage);
classMessage.id = tabMsg[0];
classMessage.innerHTML += '<button onclick="del(' + tabMsg[0] + ')">Try it</button>'

function del(parsedata) {
console.log(parsedata)
}

tabMsg is a parsed line (with split).

i dont understand why when i click on the button the output on the console is :

<class id="vuwzbip6dr"><button onclick="del(vuwzbip6dr)">Try it</button><p>gfdgf gdfgf</p></class>

why he dont put the id vuwzbip6dr !!! ?

Encapsulating strings with strings within strings generally causes more problems than it solves and therefore should be avoided.

In your case that means this statement:

'<button onclick="del(' + tabMsg[0] + ')">Try it</button>' is causing the issue for you.

That line is interpreted as:

<button onclick="del(v)">Try it</button>

Where v becomes an identifier pointing to the this , or the currentTarget element and not a string like this: "dev('v')".

Looking at the documentation one sees the onclick handler is provided the currentTarget as the first argument to the callback - hence the assignment I mention.

To fix this you should rely on the tools JavaScript provides - namely, it gives you the currentTarget (target element of the click), so all you have to do is use that and ask for it's parent element's id attribute:

classMessage.innerHTML += '<button onclick=del(this)>Try it</button>'

function del(target) {
    console.log(target.parentNode.id)
}

But that isn't recommended either. You should always try to avoid using in-line event handlers. I'll leave that to a different question for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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