我正在寻找一种方法,使页面上的所有链接都可以在新选项卡中打开。但这应该只适用于 block 内的链接。
这是应该找到页面上所有 block 的代码段。
jQuery.fn.PageBlocks = function() {
$("*").filter(function(index) {
var $this = $(this);
var tagName = $this.prop("tagName").toLowerCase();
return $this.css("display") == 'block' || tagName == 'div';
});
}
现在我想在应该修改链接的 target
属性的函数中使用此代码。
$(document).ready(function(){
var res = $(document).PageBlocks();
$.each(res, function(index, val) {
val.querySelectorAll('a').attr("target", "_blank");
});
});
看来我做错了。我如何正确制作它? 谢谢。
最佳答案
这段代码现在可以工作了。在您的代码中 jQuery.fn.PageBlocks
不工作并且 $(document).PageBlocks()
返回未定义。工作 link
<head>
<meta charset="utf-8" />
<title>HTML5</title>
</head>
<body>
<div class="MyBlock"><a href="http:\\goo.me">Link</a><br> </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
</script>
</body>
</html>
<script>
$(document).ready(function() {
var res = $("*").filter(function() {
var $this = $(this);
var tagName = $this.prop("tagName").toLowerCase();
return $this.css("display") == 'block' && tagName == 'div';
});
// console.log(res);
$.each(res, function(index, val) {
$(val).find('a').attr("target", "_blank");
});
})
</script>
关于javascript - 如何使 block 中的所有链接在新选项卡中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57257782/