Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

javascript - add an onclick event to a div

I don't know if this is allowed or even possible. Is it possible to create a div element with an onclick event so that if anywhere in the div's area is clicked, the event will run.

Eg JAVASCRIPT:

var divTag = document.createElement("div");
divTag.id="new-ID"; 
var onClickCommand = "printWorking()"   //printworking is another method that simply print "I'm working" to the console
divTag.onclick = onClickCommand;
console.log("onclick command added");
console.log(divTag.onclick);
parentDiv.appendChild(divTag); //This simply adds the div tag to the page.

HTML generated:

 <!--<div id="new-ID">-->

 whatever content I decide to add to the divTag.innerHTML

I notice how theres no onclick command going through to the generated div. Id this because its not allowed?

So 2 questions then.

1:Is it possible to add onclick to a div and have it occur if any area of the div is clicked. 2:If yes then why is the onclick method not going through to my div.


How very odd:

divTag.setAttribute("onclick", "printWorking()");

Above works flawlessly.

All below don't and wont pass the onclick to the div.

divTag.onclick=printWorking;

divTag.onclick="printWorking";

divTag.onclick="printWorking()";

Multiple other variants have been tried too.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

If yes then why is the onclick method not going through to my div.

You are assigning a string where a function is expected.

divTag.onclick = printWorking;

There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...