开发者

jQuery how to set click on href in the div?

Good day,

I want to set click event on every anchor element in my div container. Here is an example what I want to do:

---HTML---
<div id="my-container">
    <a href="page1.html">page1</a>
    <a href="page2.html">page2</a>
    <a href="page3.html">page3</a>
</div>

---- jQuery 开发者_如何学Go----
$("#my-container a").click(function() {
    var link = $(this).attr("href");
    $("#my-container").load(link);
});

What I want to do is to let me handle loading event of href clicks and load it to the same container. And this is must done without id, class attributes which aren't available for that hrefs. The problem is in this: $("#my-container a"). Any help would be appreciated! Thanks

UPDATE

People doesn't seem to get right what I wanted to ask. I repeat myself again. $("#my-container a") <---- doesn't add click events on href anchors. So how I can set click event?


Try this, wasn't sure if you were missing any tags so I've put the whole thing in:

<script type="text/javascript">
     $(document).ready(function(){
        $("#my-container a").click(function(event) {
            alert('test');
            var link = $(this).attr("href");
            $("#my-container").load(link);

            event.preventDefault();
        });
     });

</script>


You forgot to quote the href string literal:

var link = $(this).attr("href");
                        ^    ^

Also, you will need to cancel the default behavior of the click event. Currently, your event handler would fire, but you would not see the result, as the browser continues to follow the link you have clicked. Add a return false; as the last line of the event handling function to cancel this behavior.


Add return false;.

$("#my-container a").click(function() {
    var link = $(this).attr("href");
    $("#my-container").load(link);
    return false;
});


You can do like:

$(function(){
    $("#my-container > a").click(function() {
        var link = $(this).attr('href');
        $('#my-container').load(link);
        return false;
    });
});

But if you meant that you don't want to give the div any id or class then any div having links inside it will also be affected. So you should at least give the id to the div you want to load the content in.


Have you tried it with the bind function:

$("#my-container a").bind("click", function() {
    var link = $(this).attr("href");
    $("#my-container").load(link); 
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜