jQuery “.on( 'click' ,…)” does not work with LET variable declaration. But works VAR

有些话、适合烂在心里 提交于 2019-12-13 06:39:00

问题


Is this a jquery bug? I have a simple click event. When I use LET to declare some variables with image links, the click event stops working on my ipad (chrome). When I switch to LET all works.

PS: I had another question with the same code but this is completely different.

// WHEN I USE "VAR" ".on( 'click' ,....)"
// works on mobile. With "LET" it does not.

let imageLink25 = "http://s020.radikal.ru/i709/1701/58/89fe5a582b92.png ";
let imageLink50 = "http: //i056.radikal.ru/1701/3e/0c7dcfd4956b.png";
let imageLink80 = "http://s011.radikal.ru/i318/1701/56/48fc3db701a0.png";

$('.size-list-item').on('click touchend', function(event) {
  event.preventDefault();

  $(".size-list-item").removeClass('active');
  $(this).toggleClass('active');
});
.active {
  font-size: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu-list size-list-items">
  <a class="size-list-item" data-type="25m2" href="#000" onclick="void(0)">25м2</a>
  <a class="size-list-item active" data-type="50m2" href="#000" onclick="void(0)">50м2</a>
  <a class="size-list-item" data-type="80m2" href="#000" onclick="void(0)">80м2</a>
</div>

回答1:


The let variables is only available in it's block scope. In your case, you can't use the three let variables if they are outside the jQuery block.

Here's a link that explain well the difference between var, let and const.
https://www.sitepoint.com/preparing-ecmascript-6-let-const/




回答2:


I don't see that you even used the defined variables imageLink*.

It's possible that your browser doesn't support let statements. According to Can I Use? it's fully supported by default in Chrome 49 and above.

If it's not supported it'll cause syntax error preventing JavaScript from further execution. That means, your click event will never be set!

Check which version of Chrome you're running on your iPad. If it's below 49, that's your answer.

However, if the version is between 41 and 48 it's still possible to use let, but you need to be in strict mode. Simply, it requires you to put 'use strict'; at the beginning of your JavaScript code. ;-)



来源:https://stackoverflow.com/questions/41655144/jquery-on-click-does-not-work-with-let-variable-declaration-but-wo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!