jquery - 有没有更优化的方法来编写这个 _blank 属性到目标链接(在新选项卡中打开它们)的 jQuery 代码?
问题描述
这是我正在使用的代码。这是编写它的最佳方式吗?我能做得更好吗?
// Open External URLs and PDFs in New Tab
$(document).ready(function () {
$(document).on("click", 'a[href^="http"]', function () {
$(this).attr("target", "_blank");
});
$(document).on("click", 'a[href$=".pdf"]', function () {
$(this).attr("target", "_blank");
});
});
解决方案
您可以将选择器组合成一个事件监听器
$(document).on("click", 'a[href^="http"], a[href$=".pdf"]', function () {
$(this).attr("target", "_blank");
});
推荐阅读
- flutter - 颤振-'initialValue == null || 控制器 == null':不正确。表单小部件中的错误
- go - 如何使用 GIO 库使窗口居中
- powershell - Powershell在脚本中使用数组中的字符串
- haskell - 具有自定义类型的 Haskell Church 数字
- json - 如何将 Cytoscape 网络保存为平面 JSON?
- reactjs - 输入'{孩子:ReactNode; }' 与类型 'IntrinsicAttributes' 没有共同的属性
- csv - raise KeyError(key) from err KeyError: 'Sales'
- javascript - 尝试插入文本,如何找到特定对象所在的 Doc?
- ios - 从 UIViewController 实现自定义基类后,Appcenter 不会构建 iOS
- git - 如何修复被 git reset HASH 弄乱的本地副本