我想阻止 anchor
链接在 document
body
上打开,而是在 div
中呈现.我使用过 e.preventDefault()
但我认为 JQuery 并未针对该事件。
我正在以编程方式创建一个 ul
并从 array
项中向其附加 li
,然后附加 ul
到 div
。结构如下所示:
//this is just a structure, not the actual HTML
<div id="results">
<ul> .ulStyle
<li> .list-group-item
-header
-p .lead
-a .anchorStyle
</li>
</ul>
</div>
然后,我将类
添加到每个元素
。除了 ul
之外的所有内容都获得了 class
,我认为这可能就是为什么它不针对 anchors
的原因。
jQuery:
$(function(){
console.info('** anchor-tag click handler **')
/*
I've tried variations on the targeting from a
single $('.anchorStyle') to what you see below.
*/
$('div #results ul .ulStyle li .list-group-item a .anchorStyle')
.click(function(e) {
e.preventDefault();
$('#results').empty();
$('#results').load( this.getAttribute('href') );
console.log('anchor clicked...');
});
});
我在 reload
时收到第一条 console
消息,但在 click
时没有收到第二条消息。
问题:
我是否需要
ul
上的类才能正确定位它?我只是补充 为此,将它发送到ul
。这段代码是否与其他所有代码一起执行,
ul
可能尚未创建? JS/jQuery 应该 仍然bind
并继续监听event
如果它存在 - 或者在这个 案例,在click 事件
触发后找到我要定位的element
, 不是吗?
最佳答案
代码中的几个问题需要指出...
首先是选择器不对。你的元素之后有一个 空格,它是 class
这是错误的(例如:ul .ulStyle
这里 .ulStyle 被认为是 ul 的子级)。选择器必须像这个
$('div#results ul.ulStyle li.list-group-item a.anchorStyle')
注意我已经删除了元素和它的类之间的空格..
即使完成此更改,它仍然对您不起作用,因为元素是动态添加的。从 OP 中获取这条线
I'm programmatic-ly creating a ul and appending li's to it from array items then appending the ul to a div.
因此需要使用事件委托(delegate)
语法必须改为
$(document).on('click','div#results ul.ulStyle li.list-group-item a.anchorStyle',function(){//你的东西在这里});
此外,您可以使选择器保持简单
'#results a.anchorStyle'
关于javascript - 在 div 中打开一个 anchor 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38065624/