我正在用一些类ID回显一些php行,并且需要能够将它们与jquery .click一起使用作为选择器。有没有办法做到这一点??该属性没有加载其他内容,它是稍后由 php 添加的。
玩.js-
$(".link").click( function(){
/* var l = ""
$.post('input_commands/move_to.php',{l:l}, function(data) {
text=data;
elem = $("#placeholder");
//delay=100;
addTextByDelay(text,elem,delay);
}); */
alert("omg whyyyyy");
});
get_locations.php -
if($array_loc['loc_north']>0){echo "<a class='link' id='location_north'>Go north to ".$array_loc_north['loc_name']."</a> <br>";}
您需要使用委托事件,因为您的元素是动态添加到 DOM 中的(或在创建事件处理程序之后)。
$(document).on('click', '.link', function(){
console.log("clicked");
});
在上面,事件被委派给文档,因此所有点击都将根据.link
选择器进行检查,即使目标是委托事件时不存在的元素。
为了
将事件绑定到动态元素(在第一次 DOM 加载后添加的元素),
取代:
$(".link").click( function(){
跟:
$(document).on('click', '.link', function(){
希望有帮助。
如果使用 ajax 动态添加它,您可能希望调用该选择器并在回调上附加 .click()。
$.ajax({
url: '...',
success: function(response) {
// do stuff with response (assume that .link will be appended)
$(".link").click( function(){
//stuff when click link
}
}
});
否则,您可以使用 onclick 属性输出链接并定义自定义函数:
if($array_loc['loc_north']>0){echo "<a class='link' id='location_north' onclick='customFunction(this)'>Go north to ".$array_loc_north['loc_name']."</a> <br>";}
在 JS:
function customFunction(element) {
//do stuff here after the link was clicked
//element variable passed as parameter contains the link element clicked
}
PS:如果有多个元素,则不可以为"id"属性指定常量值,因为它应该是唯一的。