javascript - jQuery 链接不起作用

标签 javascript jquery html

我有一些 jQuery 可以创建链接,但是这些链接应该触发更多的 jQuery 但它们没有,这是代码:

$(".divisionLinks").click(function () { 
  $('.show_hide_division').show();
  $('.show_hide_main').html($(this).html()+ " is Selected");
  //Load the division xml
  var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async="false";
  xmlDoc.load("xml//division//"+ $(this).html() + ".xml");
  theEnvNodes = xmlDoc.getElementsByTagName('ENVIRONMENT');
  //Make the html
  theNewHTML = "<ul>";
    for (i = 0; i<theEnvNodes.length; i++){
    theNewHTML = theNewHTML + "<li><a class=\"environmentLinks\" href=\"#\">";
    theNewHTML = theNewHTML + theEnvNodes[i].childNodes[0].childNodes[0].nodeValue;
    theNewHTML = theNewHTML + "</a></li>";
    }
  theNewHTML = theNewHTML + "</ul>"; 
  $('.environmentButtons').html(theNewHTML);
});
$(".environmentLinks").click(function () { 
  $('.show_hide_environment').show();
  $('.show_hide_division').html($(this).html()+ " is Selected");
});

因此分区链接有效,但环境链接无效。 我一直在阅读它可能与 jQuery 索引 .environmentLink 类有关。但我不知道,也不知道有什么变通办法。 提前感谢您的帮助。

最佳答案

由于您是动态添加 .environmentLinks,因此不会附加您拥有的点击事件,因为加载页面时这些链接不存在。如果您使用的是最新版本的 jQuery,请使用 .on() 将点击事件绑定(bind)到 .environmentLinks 链接。

$("body").on('click', '.environmentLinks', function () { 
  $('.show_hide_environment').show();
  $('.show_hide_division').html($(this).html()+ " is Selected");
});

理想情况下,您希望将 $("body") 替换为 .environmentLinks 的父元素,该元素比 body 元素更接近它。

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

关于javascript - jQuery 链接不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11335101/

相关文章:

javascript - 没有jquery的移动设备的Mousedown事件?

javascript - Uncaught ReferenceError : addRecord is not defined at HTMLButtonElement. onclick

html - id 内的 css div 类

javascript - 仅当我以另一种方式更改对象时,下划线才会起作用

javascript - 保存父级构建树形数组

javascript - 反转页面上除图像之外的所有内容

javascript - 无法将对象传递到 Chrome 本地存储

jquery - JQuery中解析JSON的回调函数

html - css nth-child 选择器不工作

javascript - 如何将变量从@Input 传递到 Angular2 组件中的服务>