当前位置: 动力学知识库 > 问答 > 编程问答 >

ajax - How to pass an id to $.click in jQuery

问题描述:

I have the following code which

<a href="#example" id="showtext">view text</a>

$("#showtext").click (function () {

$.post('/app/foo/bar/1', function (data){

$("#msg").html(data);

});

$('#example').modal()

});

When view text is clicked I'm making a post request out to /app/foo/bar/1 and putting that data in a div with id #msg. All of this is working fine, however, now I would like to be able to pass different ids to this url, for example: /app/foo/bar/2 or /app/foo/bar/3 etc..

What is a good way to accomplish this?

One way I've thought of is to append the id to the attribute, like so:

<a href="#example" id="showtext${id}">view text</a>

and then parse out the id in jQuery using regex. However, this approach seems messy. Is there a more elegant way to accomplish this?

网友答案:

Assuming you need the href attribute left as it is, you can use a data attribute instead.

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

Or, as I mentioned you could use the 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()
});
分享给朋友:
您可能感兴趣的文章:
随机阅读: