【问题标题】:$(this).data is not working$(this).data 不工作
【发布时间】:2014-07-30 17:10:39
【问题描述】:

我已经研究了过去 2 个小时,但无法让它发挥作用。

我正在通过 ajax 加载内容,而 $(this).data 根本不适合我。如果我将 this 更改为实际的类,则内容会加载,但这是一个投资组合,因此每个按钮都有不同的 url 来加载。

HTML:

<a class="button" href="#project-full" data-work-item="portfolio-open.html">View Project</a>

JS:

var loadUrl = $(this).data('work-item');

$(".button").click(function(){
    $("#project-full").html(ajax_load).load(loadUrl);
      $("html, body").animate({ scrollTop: $('#project-full').offset(0,100).top }, 1000);
});

理论上,变量 loadUrl 不应该抓取“portfolio-open.html”并将其传递给下面的 loadUrl 吗?我确信我遗漏了一些重要的东西,但从我读过的所有来源来看,这应该工作..

【问题讨论】:

  • 请提供小提琴。
  • $(this) 指的是什么..?你能展示你的完整代码吗...!
  • 在上述上下文中this 是什么
  • ajax_load 来自哪里?
  • $(this) 应该为特定事件封装,例如 Button.click =>{ 现在使用 this 来指代 Button }

标签: javascript jquery ajax html custom-data-attribute


【解决方案1】:

你的代码应该是这样的:

$(".button").click(function(e){
    e.preventDefault();
    var loadUrl = $(this).data('work-item');
    $(this.href).load(loadUrl);
    //$("html, body").animate({ scrollTop: $('#project-full').offset(0,100).top }, 1000);
});

【讨论】:

    【解决方案2】:

    您需要将loadUrl 定义放在点击事件处理程序中,因为$(this) 应该引用您点击的锚元素:

    $(".button").click(function(e) {
        e.preventDefault(); // stop the default anchor action
        var loadUrl = $(this).data('work-item');
        $("#project-full").html(ajax_load).load(loadUrl);
          $("html, body").animate({ scrollTop: $('#project-full').offset(0,100).top }, 1000);
    });
    

    不要忘记阻止默认锚点操作(重定向)。

    【讨论】:

    • 哇。您在发布后 2 分钟内解决了我的问题,这一事实令人难以置信。非常非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-04
    • 2016-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多