[英]JQuery Append html5
我有一个标签<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...");
}
}
现在,我有40个<a href="">
链接,并且用户单击其中之一。 我需要访问此<a href="">
并对其进行处理。
我该怎么做? 谢谢
您的问题对我来说不是很清楚。
如果要确定单击了哪个,则以下代码段可能会对您有所帮助。
$("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>
尝试将类添加到<a>
标记中,并将添加的类用作click事件的选择器,然后使用this
指针/引用访问clicked标记。
参见以下示例-
<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());
});
工作小提琴-http: //jsfiddle.net/pp8b7aec/
动态添加元素时,您需要使用事件委托语法,因为页面加载时它们不在dom中,因此不会注册动态元素上的任何事件。
语法为:
$(staticParent).on('event', 'selector', fn);
因此,您可以执行以下操作:
$(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.
});
});
在上面的代码中,您甚至可以委托给$("#matrix"), $("body") or $(document)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.