jQuery if $('img').attr("src", "")
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10265144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
if $('img').attr("src", "")
提问by Jordan Lovelle
I'm trying to use jQuery to edit the SRC of an image if it's blank. Here's my current code:
如果图像为空白,我正在尝试使用 jQuery 来编辑图像的 SRC。这是我当前的代码:
<script type="text/javascript">
$(document).ready(function() {
var $this = $(this),
img = $('img');
if img.attr("src", ""){
$this.attr("src", "default.gif");
}
});
</script>
It's not working. The current error I get in my Chrome Console is:
Uncaught SyntaxError: Unexpected identifier
Can anyone help out? Thanks a lot in advanced.
- Jordan.
它不起作用。我在 Chrome 控制台中遇到的当前错误是:
Uncaught SyntaxError: Unexpected identifier
谁能帮忙?非常感谢先进。
- 乔丹。
回答by David says reinstate Monica
attr()
gets, or sets, the attribute. It doesn't assess/compare them. What you need to do is:
attr()
获取或设置属性。它不评估/比较它们。你需要做的是:
if ($this.attr('src') == '')
$this.attr('src','default.gif');
}
Or, slightly faster/more efficient:
或者,稍微更快/更有效:
var that = this;
if (that.src == ''){
that.src = 'default.gif';
}
And, as noted, the error message was presumably caused by the omission of the brackets around the if
statement to be assessed.
而且,如前所述,错误消息可能是由于省略了if
要评估的语句周围的括号造成的。
References:
参考:
回答by Parimal
Please give semicolon after this.
请在此后加分号。
var $this = $(this);