gpt4 book ai didi

javascript - 如何使用 javascript 将链接设为 "access only"

转载 作者:可可西里 更新时间:2023-10-31 23:02:02 25 4
gpt4 key购买 nike

我有一个 arduino webserver 服务器和一个 normal webserver该服务器之间的通信使用链接系统,例如:

Arduiono 服务器的普通网络服务器:

  • ArduinoServer/light1=on - 灯亮
  • ArduinoServer/light1=off - 灯熄灭

Arduino 网络服务器到普通网络服务器:

  • NormalWebserver/temperature=22&humidity=56&light1=on
  • NormalWebserver/temperature=22&humidity=56&light1=off

通信运行良好,但问题出在操作按钮上,当我切换灯时,我需要只是访问永恒的arduino websever链接和我我还使用 ajax 来检查 light 语句。

如果更改了 light 语句,我的 div.id="light1"将采用新的 javascript 内容,而我用于防止重定向到 arduino webserver 的旧代码将不再工作。

“仅访问”按钮中链接的旧代码:

// Attach click handler to all 'access-only' links.
$('a.access-only').click(function() {
// Once the link is clicked, access its URL with a GET request.
$.get($(this).attr('href'), function(response) {
// Do nothing here, the URL has been accessed.
});

// Return false to prevent the browser's default click action.
return false;
});

但即使使用来自 ajax 的新内容,我也需要一个代码来执行此操作。

最佳答案

您必须使用事件委托(delegate) 而不是事件处理程序,因为您有动态生成的内容。在您的 $.get 上,您可以删除回调。如果您不想做任何进一步的事情,则不需要。并且您应该使用 preventDefault 来中断 a 标记上的 click 执行。

$(document).on('click', 'a.access-only', function(e) {
e.preventDefault();
$.get($(this).attr('href'));
return false;
});

关于javascript - 如何使用 javascript 将链接设为 "access only",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39204526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com