【问题标题】:jQuery method .attr() insted of 'id' tracked element returning undefined. Waypoints plugin is used for trackingjQuery 方法 .attr() insted 的“id”跟踪元素返回未定义。 Waypoints 插件用于跟踪
【发布时间】:2018-05-26 19:06:34
【问题描述】:
<body>
<div id="wayp-1" class="tracked">WAY</div>
<div id="wayp-2" class="tracked">WAY</div>
<div id="wayp-3" class="tracked">WAY</div>
<script src="lib/jquery.min.js"></script>
<script src="lib/jquery.waypoints.min.js"></script>
<script>
    $('.tracked').waypoint(function(){
        alert( $(this).attr('id') );
    })
</script>

由于某种原因,此代码返回未定义。

【问题讨论】:

  • 请做一个jsfiddle
  • 你确定$(this)指的是被滚动的元素吗?
  • 第一个:给我们完整的错误或者它只是未定义??第二个:这个插件的链接在哪里?
  • 不是这里的问题,但在一般意义上,this.id 是一种比$(this).attr('id') 更好的检索元素 ID 的方法。

标签: javascript jquery undefined attr jquery-waypoints


【解决方案1】:

根据 Waypoints 文档,此插件不会接受 $(this) 作为显示元素,而是建议您在使用 jQuery 时使用 this.element。你的代码应该这样编辑:

jQuery:

$('.tracked').waypoint(function(){
    handler: function(direction) {
        notify(this.element.id + ' hit')
    }
});

或者当你使用纯javascript(不是jQuery)时,你可以使用this来访问元素属性,而不是$(this)

var waypoint = new Waypoint({
    element: document.getElementsByClassName('tracked'),
    handler: function(direction) {
        notify(this.id + ' hit')
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-20
    • 1970-01-01
    • 2015-04-09
    • 2014-01-19
    • 1970-01-01
    相关资源
    最近更新 更多