[英]JavaScript Click function element.click not working
I have javascript method which will remove applied class from DOM element on click. 我有javascript方法,可在单击时从DOM元素中删除应用的类。 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: HTML代码是:
<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 所以我希望当我在li项目控制台上单击时应该打印
CALLED toggleSortableClickHandler
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": 如果要通过DOM属性安装事件处理程序,则它是“ onclick”,而不是“ click”:
element.onclick = function onClick(e) {
console.log("CALLED toggleSortableClickHandler")
};
However, you're apparently using jQuery anyway, so you might as well use it: 但是,您显然仍在使用jQuery,因此您也可以使用它:
$(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.
您要做的不是纯JavaScript,而是jQuery,语法也不正确。
In JavaScript, 在JavaScript中,
element.click();
triggers the click event on element. 触发元素上的click事件。 In jQuery, if you want to assign a function to click event handler, you should use the syntax
在jQuery中,如果要分配一个函数来单击事件处理程序,则应使用以下语法
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. 我还建议更改处理程序函数的名称,因为onClick是HTML语言中用于指定click事件处理程序的属性。 This may create some confusion in the readability of your code.
这可能会在代码的可读性方面造成一些混乱。
By the way, onClick is used like this, fyi. 顺便说一句,onClick就是这样使用的。
<div onClick="myFunction()"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.