简体   繁体   English

如何在JQuery中转换addEventListener函数?

[英]How to convert addEventListener function in JQuery?

i'm new in jQuery and would like to convert this javascript code in jQuery 我是jQuery的新手,想在jQuery中转换此javascript代码

var trigger = document.querySelectorAll('.item');
for (var i = 0; i < trigger.length; i++) {
     trigger[i].addEventListener('click', function () {
        if (this == trigger[0]) {
            position = '1';
        } else if (this == trigger[1]) {
            position = '2';
        }
        .......
} 

A long list of if{..}else{...} is a codesmell, no matter if you're using vanilla JS or jQuery. 如果您使用的是普通JS或jQuery, if{..}else{...}的一长串代码就是代码。 That is the bit you should be solving, and jQuery makes that easier using index() 就是您应该解决的问题,jQuery使用index()使其变得更容易

 $('ul').on('click','.item',function(){ var position = $(this).index()+1; console.log(position); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class="item">Item1</li> <li class="item">Item2</li> <li class="item">Item3</li> <li class="item">Item4</li> </ul> 

 var trigger = $('.item'); trigger.click(function() { if (this == trigger[0]) { position = '1'; alert('first clicked'); } else if (this == trigger[1]) { position = '2'; alert('second clicked'); } }); 
 .item { margin: 5px; display: inline-block; height: 50px; width: 50px; background-color: lightblue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='item'></div> <div class='item'></div> 

And about the error you are receiving: 关于您收到的错误:

Error "Uncaught TypeError: sizeListItem[i].on is not a function"

Please post your whole code in your post, or drop it on jsfiddle. 请在您的帖子中发布整个代码,或将其放在jsfiddle上。

Follow jquery sintax to do that. 按照jquery sintax做到这一点。 If you have more than 2 selectors, do loop in jquery is the same of javascript. 如果选择器超过2个,则jquery中的do循环与javascript相同。

 $('.item:nth-of-type(1) ').click(function() {
  position = '1';
 });
 $('.item:nth-of-type(2) ').click(function() {
      position = '2';
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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