简体   繁体   English

表内的jQuery mobile和href链接不起作用

[英]jQuery mobile and href links inside a table not working

I'm working with jQuery mobile and populating a table by using ajax, one of the fields is a href that I'm assigning a class to, to present an alert in the screen, and it does not fire anything: 我正在使用jQuery mobile并使用ajax填充表格,其中一个字段是我要为其分配类的href,以在屏幕上显示警报,并且不会触发任何操作:

I have tried by using the double quotes and single quotes without success: 我尝试使用双引号和单引号但未成功:

Double quotes: 双引号:

$("#table1").append("<tr><td><a href='#' class='linkTest'>" + element.field1 + "</a></td><td>" + element.field2 + "</td><td>" + element.field3 + "</td></tr>");

Single quotes: 单引号:

$("#table1").append('<tr><td><a href="#" class="linkTest">' + element.field1 + '</a></td><td>' + element.field2 + '</td><td>' + element.field3 + '</td></tr>');

jQuery method: jQuery方法:

$(".linkTest").click(function(){
    alert("It works");
});

The table is populated correctly but the alert is not showing up when clicked. 该表已正确填充,但单击时未显示警报。 If I add a button outside the table, it works: 如果我在表格外添加一个按钮,它将起作用:

<a href="#" class="linkTest"> TEST </a> 

I would appreciate your help, thanks! 谢谢您的帮助,谢谢!

$(".linkTest").click() won't apply to any dynamically created elements added subsequently. $(".linkTest").click()不适用于随后添加的任何动态创建的元素。 Either do $(".linkTest").click() after the dynamic content is added or bind the event to a containing element eg $('body').on('click', '.linkTest', function() { }); 添加动态内容后执行$(".linkTest").click()或将事件绑定到包含元素的元素,例如$('body').on('click', '.linkTest', function() { });

Because your link is dynamically added to DOM, so click event will not work. 由于您的链接是动态添加到DOM的,因此click事件将不起作用。

This is exactly what you looking for event Delegation and also have to prevent default function of hyperlink 这正是您要寻找的事件委托 ,还必须防止超链接的默认功能

Consider following snippet: 考虑以下代码段:

$("#table1").on('click','.linkTest', function(e){
    e.preventDefault();//for prevent default redirect
    alert("It works");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM