[英]jquery - if href attr == “”
I am trying to find out if a href attr is empty do something, my code is as follows...我试图找出href attr是否为空做某事,我的代码如下......
jQuery('#sidebar a').click(function() {
var bob = jQuery(this).attr("href");
if(jQuery(bob).attr() == "") {
alert('I am empty href value');
}
});
I am not sure where I am going wrong?我不确定我哪里出错了? Any advice?
有什么建议吗? Thanks!
谢谢!
You're passing bob
into jQuery
as a selector.您将
bob
作为选择器传递给jQuery
。 Just test it directly:直接测试一下:
jQuery('#sidebar a').click(function() {
var bob = jQuery(this).attr("href");
if (bob == "") {
alert('I am empty href value');
}
});
Or better yet, just:或者更好的是,只是:
if (!bob) {
use this instead改用这个
jQuery('#sidebar a').click(function() {
var bob = jQuery(this).attr("href");
if(bob === "") {
alert('I am empty href value');
}
});
Answer is already given by great guys.大佬们已经给出了答案。
just check if(bob=="")只需检查 if(bob=="")
I would add one more line.我会再添加一行。 Just for safety you can trim bob using jQuery.
为了安全起见,您可以使用 jQuery 修剪鲍勃。
bob = jQuery.trim(bob);
This will make the validity a bit stronger.这将使有效性更强一些。
jQuery('#sidebar a').click(function() {
if(jQuery(this).attr("href")==""){
alert('I am empty href value');
}
});
There is no use of filtering your bob again with jQuery.用 jQuery 再次过滤你的鲍勃是没有用的。 :)
:)
You are setting a variable and then never checking it.您正在设置一个变量,然后从不检查它。 Personally, I wouldn't even create a variable;
就个人而言,我什至不会创建变量。 Just do the check.
只做检查。
jQuery('#sidebar a').click(function() {
if(jQuery(this).attr("href") == "") {
alert('I am empty href value');
}
});
You are defining the attribute href
to variable bob
already.您已经将属性
href
定义为变量bob
。 Just use:只需使用:
bob == ""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.