更改url后jQuery触发点击



我有一个函数,可以记录点击带有数据标记的链接的情况。代码会隐藏一个电话号码,直到点击链接,然后显示号码。我遇到的问题是,一旦加载后,如果没有用户交互,我就无法启动显示的号码

我不得不阻止第一次点击按钮时的默认事件,因为url还没有包含真实数据,而且我不希望页面跳转

一旦点击,新链接的html将变为,例如:;☎0123456789">
并且href将更改为,例如:"电话:0123456789">
此数据是从AJAX PHP文件发送的JSON中获取的

在这之后,我想用程序点击URL,但我似乎无法启动它,并不断收到控制台错误消息,上面写着";未捕获类型错误:事件未定义">
~大概与事件有关,防止默认

信息:将通过PHP加载多个电话号码,因此我需要单独访问每个电话号码。

链接的HTML

<a data-num='$number' class='telephone' href='#'>&#9742; Click to call</a>

JS代码(jQuery 3.4.1(

$(document).on('click','.telephone',function(event) {
event.preventDefault(); // Prevent page jump
var num = $(this).data("num");
$.ajax({
url: "myserverfile.php",
method: "POST",
data: {num: num},
dataType: "json",
success: function(a) {
var b = (a[0]['status']); // True or false
var c = (a[0]['tel']); // Number or error
// If result found change URL and click it to call number
if (b == true) {
$('.telephone[data-num="' + num + '"]').html("&#9742;&nbsp;" + c); // Change link text
$('.telephone[data-num="' + num + '"]').attr("href", "tel:" + c); // Change link href
$('.telephone[data-num="' + num +'"]').click(); // Update: This causes a loop because it runs the code again. I need to hide the original a tag and create a new one then trigger it.
}
}
});
});

有什么建议吗?

调用.click()方法不会创建eventevent是在用户实际单击某个内容时创建的。如果您是console.log(event),那么当.click()调用它时,它将是undefined,这就是您得到错误的地方。为了绕过这个问题,你可以

if (event) { event.preventDefault(); }

但你会遇到递归,因为你基本上是

$(document).on('click', '.telephone', function() { $('.telephone').click(); });

为了避免这种情况,你可以添加一些类似loaded类的东西

$(document).on('click', '.telephone:not(.loaded)', function() {
$('.telephone[data-num="' + num +'"]')
.addClass('loaded')
.attr(...)
.html(...)
.click();
});

此外,您稍后会感谢自己使用了一些更具描述性的变量名。对于那些不知道的人来说,jquery是可链接的。

想明白了。我创建了一个循环,所以点击不起作用,所以我隐藏了点击后的第一个链接,并加载了一个新的隐藏链接。我为这个新链接上的数据标记使用了表中不同的列值,以避免任何可能的冲突。

除了循环问题,我缺少的主要部分是分配之前的[0]。点击.

谢谢你一路上的建议。

下面的工作代码

$(document).on('click', '.telephone', function(event) {
event.preventDefault();
var num = $(this).data("num");
$.ajax({
url: "myserverfile.php",
method: "POST",
data: {num: num},
dataType: "json",
success: function(a) {
var b = (a[0]['status']);
var c = (a[0]['id']);
var d = (a[0]['tel']);
if (b == true) {
$('.telephone[data-num="' + num + '"]').hide(200);
$(document).ready(function() {
$(".telephone-reveal");
$('.telephone-reveal[data-id="' + c + '"]').show(200);
$('.telephone-reveal[data-id="' + c + '"]').html("&#9742;&nbsp;" + d);
$('.telephone-reveal[data-id="' + c + '"]').attr("href", "tel:" + d);
$('.telephone-reveal[data-id="' + c + '"]')[0].click();
});
}
}
});
});

最新更新