我有以下代码
<a href="#example" id="showtext">view text</a>
$("#showtext").click (function () {
$.post('/app/foo/bar/1', function (data){
$("#msg").html(data);
});
$('#example').modal()
});
当点击 view text
时,我将向 /app/foo/bar/1
发出发布请求,并将该数据放入 id 的 div 中>#msg
。所有这些都工作正常,但是,现在我希望能够将不同的 ids
传递到此网址,例如:/app/foo/bar/2
或/app/foo/bar/3
等等..
什么是实现这一目标的好方法?
我想到的一种方法是将 id 附加到属性,如下所示:
<a href="#example" id="showtext${id}">view text</a>
然后使用正则表达式解析出 jQuery 中的id
。然而,这种方法似乎很困惑。有没有更优雅的方法来实现这一点?
最佳答案
假设您需要保留 href
属性,则可以使用 data
属性。
<a href="#example" id="showtext" data-url="/app/foo/bar/2">view text</a>
$("#showtext").click(function() {
$.post(
$(this).data('url'),
function(data) {
$("#msg").html(data);
}
);
$('#example').modal()
});
或者,正如我提到的,您可以使用 href
:
<a href="/app/foo/bar/2" id="showtext">view text</a>
$("#showtext").click(function(e) {
e.preventDefault(); // prevent the link being followed normally
$.post(
$(this).prop('href'),
function(data) {
$("#msg").html(data);
}
);
$('#example').modal()
});
关于jquery - 如何在 jQuery 中将 id 传递给 $.click,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14241062/