简体   繁体   中英

JQuery Append html5

I have a matrix of tags <a href=""> , generated by this code in JQuery :

function makeList(){
    var listContainer = $("#matrix");
    for(i=0; i<10; ++i){
        listContainer.append( $("<nav><ul> <li><a href="">v1</li> 
            <li><a href="">v2</li> <li><a href="">v3</li> 
            <li><a href="">v4</li>"));
        console.log("adding...");
    } 
}

Now I have 40 <a href=""> links, and a user click one of them. I need to access to this very <a href=""> and make something to it.

How can I do it? Thank you

As the elements are getting appended, initially the DOM won't have the elements. Use on event handler.

Syntax:

.on('event', 'selector', fn);

Plus using " this " keyword, you can fetch the element which you have just clicked.

 $("a").on("click",function(){
    console.log($(this).html());
 });

Have appended the elements required and added an event handler in the following fiddle .

Your question is not very clear to me.
If you want to identify which is clicked the following code snippets may help you.

 $("a").on("click",function(){ alert($(this).html()); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> <a href="#">Link 4</a> 

Try adding a class to the <a> tag and use the added class as selector for the click event and access the clicked tag using this pointer/reference.

See below example-

<a class="test" href="#">Test 1</a>
<a class="test" href="#">Test 2</a>
<a class="test" href="#">Test 3</a>
<a class="test" href="#">Test 4</a>
$('.test').on('click',function(){
alert($(this).text());
});

Working Fiddle- http://jsfiddle.net/pp8b7aec/

As you are appending the elements dynamically so you need to use event delegation syntax, because they were not in the dom when page loaded, so any event bound on dynamic elemetns won't be registered.

The syntax is:

$(staticParent).on('event', 'selector', fn);

so in your case you can do this:

$(function(){
    $("#matrix").on('click', 'nav a', function(e){ // register the event on static parent
        e.preventDefault();// stops the link to navigate
        alert(this.textContent); // alert the text written in the clicked link.
    });
});

in the code above you can even delegate to the $("#matrix"), $("body") or $(document) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM