JQuery How to set click on href in div?

Good afternoon,

I want to set a click event for every anchor element in a div container. Here's an example 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 ----
$("#my-container a").click(function() {
    var link = $(this).attr("href");
    $("#my-container").load(link);
});

      

What I want to do is let me handle the href click load event and load it into the same container. And this should be done without id, class attributes that are not available for this hrefs. The problem is this: $ ("# my-container a") . Any help would be appreciated! Thanks to

UPDATE

People don't seem to understand what I wanted to ask. I repeat myself again. $ ("# my-container a") <---- does not add click events on href bindings. So how can I set the click event?

+2


a source to share


5 answers


Try this, wasn't sure if you were missing any tags, so I 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>

      

+6


a source


You forgot to quote the string literal href

:

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

      



Also, you will need to override the default behavior of the click event. Currently your event handler will fire, but you won't see the result as the browser continues to follow the link you clicked. Add return false;

event-handling functions as the last line to reverse this behavior.

+1


a source


You can do this:

$(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 div

any id

or class

, then anyone div

with links within it will be affected . Therefore, you should at least transfer id

to div

which content you want to download.

0


a source


Add return false;

.

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

      

0


a source


Have you tried it with a function bind

:

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

      

0


a source







All Articles