简体   繁体   English

jQuery追加html5

[英]JQuery Append html5

I have a matrix of tags <a href=""> , generated by this code in JQuery : 我有一个标签<a href="">矩阵,由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. 现在,我有40个<a href="">链接,并且用户单击其中之一。 I need to access to this very <a href=""> and make something to it. 我需要访问此<a href="">并对其进行处理。

How can I do it? 我该怎么做? Thank you 谢谢

As the elements are getting appended, initially the DOM won't have the elements. 随着元素的追加,最初DOM将没有元素。 Use on event handler. 在事件处理程序上使用

Syntax: 句法:

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

Plus using " this " keyword, you can fetch the element which you have just clicked. 加上使用“ this ”关键字,您可以获取刚刚单击的元素。

 $("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. 尝试将类添加到<a>标记中,并将添加的类用作click事件的选择器,然后使用this指针/引用访问clicked标记。

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/ 工作小提琴-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. 动态添加元素时,您需要使用事件委托语法,因为页面加载时它们不在dom中,因此不会注册动态元素上的任何事件。

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) . 在上面的代码中,您甚至可以委托给$("#matrix"), $("body") or $(document)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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