【问题标题】:Replace ajax url with clicked element which have data attribute用具有数据属性的单击元素替换 ajax url
【发布时间】:2015-06-02 07:20:32
【问题描述】:

我的问题对 jquery 爱好者来说很简单,但对我来说很难。我有简单的a href 标签,包含数据属性。

<a href="#/one" data-menu-button="menu1" class="button">menu 1</a>
<a href="#/two" data-menu-button="menu2" class="button">menu 2</a>

// etc

我也有非常简单的 ajax 调用脚本。

$(".button").click(function(){
        $.ajax({url: "test.php", success: function(result){
           $(".page").html(result);
        }});
});

我的问题:

如何用单击的按钮数据属性替换 ajax url?例如,目前,如您所见,我有url: "test.php"。我需要的是将test 更改为数据属性(例如:menu1),但保留.php 扩展名。我需要该脚本找到点击的数据属性,并将其替换为test。也许$(this) 会起作用?

感谢您的任何回答,抱歉英语不好。

【问题讨论】:

    标签: jquery ajax html custom-data-attribute


    【解决方案1】:

    您可以使用 .data() 从数据属性中获取值。

    使用$(this).data('menu-button')data-menu-button 获取,然后将.php 附加到它。它看起来像menu1.php$(this) 将引用当前被点击的元素。

    您还必须使用e.preventDefault() 来阻止页面导航到 href 属性中存在的任何内容。除非您想通过页面 url 来获得这些片段。

    $(".button").click(function(e){
        e.preventDefault();
        $.ajax({url: $(this).data('menu-button') + '.php', success: function(result){
           $(".page").html(result);
        }});
    });
    

    【讨论】:

      【解决方案2】:

      如您所料,使用$(this) 访问元素,然后使用.attr('data-menu-button) 获取属性值。

      $(".button").click(function(){
          var url = $(this).attr('data-menu-button') + '.php';
          $.ajax({url: url, success: function(result){
             $(".page").html(result);
          }});
      })
      

      【讨论】:

      • 也谢谢你,但@Dhiraj Bodicherla 解释得更快 :)
      猜你喜欢
      • 2019-06-05
      • 1970-01-01
      • 2016-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多