Jquery 类及其函数

Jquery class and its function

本文关键字:函数 Jquery      更新时间:2023-09-26

我正在开发 asp.net 讨论小组,其中我正在通过javascript绘制一些跨度

$("#commenttr").after("<tr id="+i+"><td class='"labelPortion'"></td><td class='"controlPortion'">" +out[i]+ "</td><td><span style = '"cursor:pointer'" class = '"plblAgreeComment'" id = '"" + ids[i+1] + "'"> Vote Up </span> <span style = '"cursor:pointer'" class = '"plblDisAgreeComment'" id = '"" + ids[i+1] +"'">Vote Down </span><span id = '"ptxtAgreeComment'" >"+ agrees[i+1] + " </span></td></tr>");

但是当我调用 jquery 函数时

$(".plblAgreeComment").click(function(){
    alert("hi");
}

它不起作用。请帮助我。

说明

您需要 jQuery .live().on()方法将事件绑定到动态创建的 html。

选择.live().on(),具体取决于您使用的 jQuery 版本。

.live() 自 jQuery 1.3 起可用。为现在和将来与当前选择器匹配的所有元素附加事件处理程序。

.on() 自 jQuery 1.7 起可用。将一个或多个事件的事件处理程序函数附加到所选元素。

样本

$(".plblAgreeComment").live('click', function(){
     alert("hi");
});
$(".plblAgreeComment").on('click', function(){
     alert("hi");
});

更多信息

  • jQuery.live()
  • jQuery.on()

更新:jsFiddle 演示

> 使用 jQuery on,因为您要动态地将这些项目添加到 DOM 中

 $(function(){
    $("body").on("click",".plblAgreeComment",click(function(){
            alert("hi");
    });
  });

on将适用于当前元素和未来元素。

http://api.jquery.com/on/

on从jQuery 1.7开始可用,如果您使用的是旧版本的jQuery,则应选中live http://api.jquery.com/live/

尝试在下面的语法中使用.on

$(document).on('click', '.plblAgreeComment', function(){
    alert("hi");
});

在上面的代码中,使用表格选择器而不是文档选择器。

两件事..在为行生成HTML时,类名中可能会有一个额外的字符。

class = '"plblAgreeCom 

也许应该是:

class ='"plblAgreeCom 

或者您在修改 DOM 之前附加单击处理程序,在这种情况下:

 $(".plblAgreeComment").click(function(){
        alert("hi");
}

应该是:

 $(".plblAgreeComment").live("click", function(){
        alert("hi");
}

如果要将事件绑定到动态注入的 DOM 元素,则需要使用 on 方法,以便将任何新元素绑定到该事件侦听器:

 $(".plblAgreeComment").on("click", function(){
    alert("hi");
 }

注意:还有其他方法,例如live()可以实现类似的效果,但它们已被弃用,取而代之的是 on ,它可以为每个场景处理这种情况。