如何通过jquery在所有链接中添加函数
How to add function in all links through jquery?
我正在使用以下函数来加载页面。我有很多链接,无法添加到所有链接。
function LoadPage(url) {
$("#canvas").load(url);
}
我想要一个函数,它将获取所有<a>
标签href
值,并将此功能添加到所有链接中,如下所示:
var oP = document.getElementsByTagName("a"),
ctr = 0
;
while(ctr < oP.length) {
var oldHref = document.getElementsByTagName("a")[ctr].href;
document.getElementsByTagName("a")[ctr].href = "javascript:loadPage('" + oldHref + "');";
ctr++;
}
我想添加到所有链接,但不添加到"索引.HTML"。
像这样:
// select all links
$('a')
// check that the pathname component of href doesn't end with "/index.html"
.filter(function() {
return !this.href.pathname.match( /'/index'.html$/ );
// // or you may want to filter out "/index.html" AND "/", e.g.:
// return !this.href.pathname.match( /'/(index'.html)?$/i )
})
// add a click event handler that calls LoadPage and prevents following the link
.click(function(e) {
e.preventDefault();
LoadPage(this.href);
});
由于您是动态加载页面的各个部分,因此需要改为设置事件委派。具体如何执行此操作取决于您使用的jQuery版本,但您将使用.on()
(jQuery 1.7+)或.delegate()
(jQuery 1.7之前)函数。.on()
示例如下所示:
$('body').on('click', 'a', function(e) {
if(!this.href.pathname.match( /'/index'.html$/ )) {
e.preventDefault();
LoadPage(this.href);
}
});
在回答您关于在新加载的页面上转换链接的问题时,$.load()
为回调函数提供了第二个参数,您可以使用该参数将像@AnthonyGrist这样的函数应用于新内容,例如:
function loadPage( url ) {
// add a callback to $.load() to be executed for the next content
$("#canvas").load( url, function() { convertLinks( this ); } );
}
function convertLinks( context ) {
// select all links in the given context
$( 'a', context )
// check that the pathname component of href doesn't end with "/index.html"
.filter(function() {
return !this.href.pathname.match( /'/index'.html$/ );
// // or you may want to filter out "/index.html" AND "/", e.g.:
// return !this.href.pathname.match( /'/(index'.html)?$/i )
})
// add a click event handler that calls LoadPage and prevents following the link
.click(function(e) {
e.preventDefault();
loadPage( this.href );
})
;
}
// call convertLinks on the whole document on initial page load
$( function() { convertLinks( document ); } );
使用.on()
也是一个合理的解决方案。
相关文章:
- 正在链接添加了以下内容::在之后
- 将超链接添加到“;标题“;标记文本
- 将重定向URL链接添加到JS函数
- 如何将超链接添加到通过传单创建的传单多段线.Draw
- 将数据库中的超链接添加到查询结果
- jQuery regex从文本链接-添加不需要的域到链接
- 将href链接添加到通过js鼠标悬停显示的图像
- 三.js - 自 r69 以来如何链接/添加相机灯
- 如何向超链接添加变量值
- 使用JavaScript向链接添加参数
- 知道点击了什么链接添加到数据库中
- 向asp.net生成的链接添加确认javascript
- 使用AJAX将AJAX链接添加到页面Yii
- 如何仅为特定URL向超链接添加属性
- 如何在javascript中将下一个和上一个链接添加到当前滑块
- 如何通过Jquery点击链接添加输入
- 将带有单击事件的超链接添加到 Dojo 网格
- OpenCart - 通过链接添加产品
- 使浏览器为我的链接添加书签
- 使用 JavaScript 向一组链接中的第一个链接添加一个属性