Javascript 执行功能时添加的动态选择器

Javascript 执行功能时添加的动态选择器,javascript,php,jquery,Javascript,Php,Jquery,我正在用一些类id回显一些php行,需要能够将它们与jquery一起使用。有没有办法做到这一点??该属性并不是与其他所有内容一起加载的,它是稍后由php添加的 play.js- $(".link").click( function(){ /* var l = "" $.post('input_commands/move_to.php',{l:l}, function(data) { text=data; elem = $("#placeholder");

我正在用一些类id回显一些php行,需要能够将它们与jquery一起使用。有没有办法做到这一点??该属性并不是与其他所有内容一起加载的,它是稍后由php添加的

play.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");
});
获取_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>";}
if($array\u loc['loc\u north']>0){echo“转到北方”。$array\u loc\u north['loc\u name'])。“
”;}
为了将事件绑定到动态元素(第一次加载DOM后添加的元素)

替换:

$(".link").click( function(){
与:


希望能有所帮助。

您需要使用委派事件,因为您的元素是动态添加到DOM的(或在创建事件处理程序之后)


在上面的例子中,事件被委派给文档,因此所有的点击都将根据
.link
选择器进行检查,即使目标是委派事件时不存在的元素。

如果它是使用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>";}

PS:如果有多个元素,那么为“id”属性指定常量值是不合适的,因为它应该是唯一的

,所以您要问jquery如何从php文件中引用或调用数据,单击?
$.ajax({
        url: '...',
        success: function(response) {
            // do stuff with response (assume that .link will be appended)
            $(".link").click( function(){
                //stuff when click link
            }
        }
    });
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>";}
function customFunction(element) {
 //do stuff here after the link was clicked
 //element variable passed as parameter contains the link element clicked
}