add an onclick event to a div

后端 未结 3 999
长发绾君心
长发绾君心 2020-12-16 09:54

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

相关标签:
3条回答
  • 2020-12-16 10:24

    Everythings works well. You can't use divtag.onclick, becease "onclick" attribute doesn't exist. You need first create this attribute by using .setAttribute(). Look on this http://reference.sitepoint.com/javascript/Element/setAttribute . You should read documentations first before you start giving "-".

    0 讨论(0)
  • 2020-12-16 10:27

    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

    0 讨论(0)
  • 2020-12-16 10:37

    Assign the onclick like this:

    divTag.onclick = printWorking;
    

    The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking).
    The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>, but this is generally not recommended.

    0 讨论(0)
提交回复
热议问题