我在一个页面上列出了一些用户生成的链接。问题是,并不是所有用户都在他们的url中添加"http://",这会把事情搞砸。
作为回应,我使用了这段jQuery(由于noconflict模式,"$"被"jQuery"替换)来检测是否存在http://,如果不存在,则添加它:
jQuery('.theirsite').each(function(){
var currentlink = jQuery(this);
var linkloc = currentlink.attr('href');
var httpcheck = linkloc.substr(0,7);
if(httpcheck!="http://"){
currentlink.attr('href','http://'+linkloc);
}
});
但它不起作用,我在Chrome的控制台上看到了这个错误:
Uncaught TypeError: Cannot read property 'substr' of undefined (index):456
(anonymous function) (index):456
x.extend.each jquery.js:3
x.fn.x.each jquery.js:3
(anonymous function)
这是我正在使用的php:<div class="theirsite"><?php echo '<a href="' . $user_info->user_url . '" class="button"> Visit their website </a>';?></div>
整个事情都在WordPress上。如果我遗漏了什么或没有看到任何明显的东西,我深表歉意。感谢所有的指点。
您的.theirsite
元素没有href
属性,它是div
。
您应该更改:
jQuery('.theirsite').each(function(){
类似于:
jQuery('.theirsite a').each(function(){
也许这样可以:
首先,我将jQuery声明为$,所以您不必一直键入jQuery。然后是准备好的处理程序。然后在每个部分中,查找a元素并检查url是否包含http://我还写了https的检查。应该有效。。
(function($) {
$(function() {
$('.theirsite').each( function() {
url = $(this).find("a").attr("href");
if (url.indexOf("http://") !== -1 && url.indexOf("https://") !== -1) {
$(this).attr("href", "http://" + url);
}
});
});
})(jQuery)