helloxielan 2014-06-10 03:49 采纳率: 0%
浏览 213

$(this).data不起作用

I've researched for the past 2 hours and cannot get this to work.

I am loading content via ajax and $(this).data is not working for me at all. If I change this to the actual class, then the content does load, however this is a portfolio so every button has a different url to load.

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);
});

In theory, shouldn't the variable loadUrl grab the "portfolio-open.html" and pass it over to the loadUrl below? I am sure that I am missing something important, but from all the sources I've read this should work..

  • 写回答

2条回答 默认 最新

  • 零零乙 2014-06-10 03:51
    关注

    You need to put the loadUrl definition inside the click event handler, because $(this) should refer to the anchor element you've clicked:

    $(".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);
    });
    

    Don't forget to prevent the default anchor action (redirecting).

    评论
  • 笑故挽风 2014-06-10 04:02
    关注

    Here is what your code should be:

    $(".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);
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 存储过程或函数中的结果集类型变量如何使用。
  • ¥80 关于海信电视聚好看安装应用的问题
  • ¥15 vue引入sdk后的回调问题
  • ¥15 求一个智能家居控制的代码
  • ¥15 ad软件 pcb布线pcb规则约束编辑器where the object matpcb布线pcb规则约束编辑器where the object matchs怎么没有+15v只有no net
  • ¥15 虚拟机vmnet8 nat模式可以ping通主机,主机也能ping通虚拟机,但是vmnet8一直未识别怎么解决,其次诊断结果就是默认网关不可用
  • ¥20 求各位能用我能理解的话回答超级简单的一些问题
  • ¥15 yolov5双目识别输出坐标代码报错
  • ¥15 这个代码有什么语法错误
  • ¥15 给予STM32按键中断与串口通信