这是JSP
$(document).ready(function() {
$("#search_button").click(function() {
$('#left_child_layout').empty();
var searchElement = document.getElementById("searchText").value;
$.post("/performSearch",{searchElement:searchElement},function(responseJson){
var $table = $('<table>').appendTo($('#left_child_layout'));
if(responseJson.length ==0){
$('<tr>').appendTo($table)
.append($('<td>').text("No results"));
}
$.each(responseJson, function(i,obj) {
$('<tr>').appendTo($table)
.append($('<td>').html('<a id="names_from_search"><u>'+obj+'</u></a>')); //line 13
});
});
});
});
因此,在第13行中,我有一个带有Id属性的<a>
标记,但是当我编写与该ID相对应的click
函数时,它似乎不起作用。
例如,当我写
时$("#names_from_search").click(function(){
alert("clicked");
});
我认为我在指定id方面出错了。指定相同的方法是什么?
答案 0 :(得分:1)
您在循环中创建了许多代码,并且您为每个人分配了相同的 ID
您需要为每个标记
分配唯一ID var count = 0;
$.each(responseJson, function(i,obj) {
$('<tr>').appendTo($table)
.append($('<td>').html('<a id="names_from_search' + count + '" ><u>'+obj+'</u></a>')); //line 13
count++;
});
然后你应该为每个id点击事件,
其他不错的选择是将click事件绑定到类而不是id 。
答案 1 :(得分:0)
尝试做这样的事情:
$.each(responseJson, function(i,obj) {
$('<tr>').appendTo($table)
.append($('<td>').html('<a id="names_from_search" onclick="return testClick(this);"><u>'+obj+'</u></a>')); //line 13
});
并添加功能:
function testClick(ref){
alert("Hi. clicked " + $(ref).html() + " || "+$(ref).text());
return false;
}
答案 2 :(得分:0)
不,指定id没有任何问题。在动态插入标记时,您需要使用$ .on()
$("#search_button").on('click', '#names_from_search', function(){
alert("clicked");
});
答案 3 :(得分:0)
将每个函数的i参数添加到锚点的id中。然后,您可以向该锚添加一个类,并将其定位到您的点击事件。
$.each(responseJson, function(i,obj) {
$('<tr>').appendTo($table).append($('<td>').html('<a id="names_from_search_"' + i + ' class="my-anchor"><u>'+obj+'</u></a>'));
});
$('.my-anchor').click(function(){
alert('clicked');
});