0

我正在用一些类 id 呼应一些 php 行,并且需要能够将它们与 jquery .click 一起使用作为选择器。有没有办法做到这一点??该属性未加载任何其他内容,稍后由 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");
});

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>";}
4

3 回答 3

0

为了将事件绑定到动态元素(在第一次 DOM 加载后添加的元素),

代替:

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

和:

$(document).on('click', '.link', function(){

希望有帮助。

于 2013-10-23T18:59:01.747 回答
0

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

$(document).on('click', '.link', function(){
    console.log("clicked");
});

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

于 2013-10-23T18:59:23.937 回答
0

If it's added dynamically using ajax you might want to call that selector and append the .click() on the callback.

$.ajax({
        url: '...',
        success: function(response) {
            // do stuff with response (assume that .link will be appended)
            $(".link").click( function(){
                //stuff when click link
            }
        }
    });

Otherwise, you can output the links with the onclick attribute and define a custom function:

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>";}

and in the JS:

function customFunction(element) {
 //do stuff here after the link was clicked
 //element variable passed as parameter contains the link element clicked
}

PS: If there are multiple elements it's not ok to specify constant value for "id" attribute because it should be unique.

于 2013-10-23T19:02:18.227 回答