将 ajax url 替换为具有数据属性的单击元素

Replace ajax url with clicked element which have data attribute

我的问题对于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) 行得通?

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

您可以使用 .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);
    }});
});

如您所料,使用 $(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);
    }});
})