如何只访问"一个链接,使用javascript

时间:2016-08-29 10:55:03

标签: javascript php jquery ajax

我有arduino webserver服务器和normal webserver 这些服务器之间的通信使用链接系统,如:

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

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

Arduino Webserver到普通网络服务器:

  • NormalWebserver /温度= 22&安培;湿度= 56&安培;光线1 =上
  • NormalWebserver /温度= 22&安培;湿度= 56&安培;光线1 =关

comunicaton运行良好,但问题在于操作按钮,当我切换灯光时,我需要just to access永恒arduino websever link而且我也使用ajax来检查光明声明。

如果更改灯光声明,我的div.id =" light1"获取新的javascript内容和我的旧代码,以防止重定向到arduino webserver不再有效。

旧代码'acces only'按钮中的链接:

// 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中的新内容,我也需要一个代码来执行此操作。

1 个答案:

答案 0 :(得分:4)

您必须使用事件委派而不是事件处理程序,因为您已动态生成内容。在$.get上,您可以删除回调。如果你不想再做任何事情,那就不需要了。您应该使用preventDefault来破解click代码上的a执行。

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