本文介绍了为什么不javascript和“这个”使用“每个”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在检测到数据投票属性true时将一个类分配给一个元素



我使用的是 $(this),直到我阅读了 each()的jQuery的文档,然后切换到以下内容:

  windowReady =  - > 
jQuery - >
$ voteLinks = $('。vote-button a')

$ voteLinks.each(i,current) - >
if(current).data('voted')==true
$(current).addClass('voted')

$ (windowReady);
$(window).on('page:load',windowReady);

$(this)






  windowReady =  - > 
jQuery - >
$ voteLinks = $('。vote-button a')

$ voteLinks.each - >
如果$(this).data('voted')==true
$(this).addClass('voted')

$ (windowReady);
$(window).on('page:load',windowReady);

但即使这还没有分配类,即使我已经确认它有数据投票属性true



CoffeesSript可以在转换为Javascript。

解决方案

作为对@gwho的回答的补充,这种隐式类型转换实际上是的功能

如上面引用的解释,如果你不喜欢隐式转换,你可能更喜欢使用 attr()属性名称)而不是 data()

  windowReady = ; 
jQuery - >
$ voteLinks = $('。vote-button a')

$ voteLinks.each(i,current) - >
if $(current).attr('data-voted')==true
$(current).addClass('voted')
/ pre>

如果你可以使用隐式转换:

  windowReady =  - > 
jQuery - >
$ voteLinks = $('。vote-button a')

$ voteLinks.each(i,current) - >
if $(current).data('voted')== true
$(current).addClass('voted')


I'm trying to assign a class to an element upon detecting that it has a data-voted attribute of "true", but the simple addClass line is not working.

I was using $(this) until I read jQuery's documentation for each(), and then switched to the following:

windowReady = ->
  jQuery -> 
    $voteLinks = $('.vote-button a')

    $voteLinks.each (i, current) ->
      if $(current).data('voted') == "true" 
        $(current).addClass('voted')

$(window).load(windowReady);
$(window).on('page:load', windowReady);

$(this)


windowReady = ->
  jQuery -> 
    $voteLinks = $('.vote-button a')

    $voteLinks.each ->
      if $(this).data('voted') == "true" 
        $(this).addClass('voted')

$(window).load(windowReady);
$(window).on('page:load', windowReady);

But even that is still not assigning a class, even though I've confirmed that it does have the data-voted attribute of "true"

CoffeesSript can be converted to Javascript at js2coffee.

解决方案

As a complement to the answer by @gwho, this implicit type conversion is in fact a documented feature of JQuery:

As explained in the above quote, if you "don't like" implicit conversion, you might prefer using attr() (using the full attribute name) instead of data():

windowReady = ->
  jQuery -> 
    $voteLinks = $('.vote-button a')

    $voteLinks.each (i, current) ->
      if $(current).attr('data-voted') == "true" 
        $(current).addClass('voted')

And if you can live with that implicit conversion:

windowReady = ->
  jQuery -> 
    $voteLinks = $('.vote-button a')

    $voteLinks.each (i, current) ->
      if $(current).data('voted') == true 
        $(current).addClass('voted')

这篇关于为什么不javascript和“这个”使用“每个”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 05:28