简体   繁体   中英

JavaScript Click function element.click not working

I have javascript method which will remove applied class from DOM element on click. And the code is like

 $(function() {

     NS.toggleSortableClickHandler = function(element) {
         console.log("elememnt inside toggleSortableClickHandler  " + element)
         element.click = function onClick(e) {
             console.log("CALLED toggleSortableClickHandler")
         }
     }

     var ele = document.getElementById('mytoggler');
     console.log("document.getElementById('mytoggler') " + ele)
     NS.toggleSortableClickHandler(document.getElementById('mytoggler'));

 });

And the HTML code is:

<ol class="sortable" >
    <li id="mytoggler">List Item 11</li>
</ol>

So i expect that when i click on the li item console should print

CALLED toggleSortableClickHandler

But i didn't get anything when i click the item.

If you're going to install an event handler via the DOM property, it's "onclick", not "click":

     element.onclick = function onClick(e) {
         console.log("CALLED toggleSortableClickHandler")
     };

However, you're apparently using jQuery anyway, so you might as well use it:

     $(element).on("click", function onClick(e) {
         console.log("CALLED toggleSortableClickHandler")
     });

First of all, you forgot the brackets, it should be

.click()

and you can't use the "=" operator after that. What you want to do isn't pure JavaScript, it's jQuery, and the syntax isn't correct.

In JavaScript,

element.click();

triggers the click event on element. In jQuery, if you want to assign a function to click event handler, you should use the syntax

element.click(yourFunction());

I would also suggest changing the name of your handler function, since onClick is an attribute used in HTML language to specify the click event handler. This may create some confusion in the readability of your code.

By the way, onClick is used like this, fyi.

<div onClick="myFunction()"></div>

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