如果图像为空白,我正在尝试使用 jQuery 来编辑图像的 SRC。这是我当前的代码:

    <script type="text/javascript">
    $(document).ready(function() {
        var $this = $(this),
            img = $('img');
        if img.attr("src", ""){
            $this.attr("src", "default.gif");
        }
    });
</script>

它不起作用。我在 Chrome 控制台中得到的当前错误是:Uncaught SyntaxError: Unexpected identifier
任何人都可以帮忙吗?非常感谢先进。
- 乔丹。

最佳答案

attr() 获取或设置属性。它不评估/比较它们。你需要做的是:

if ($this.attr('src') == '')
    $this.attr('src','default.gif');
}

或者,稍微更快/更有效:
var that = this;
if (that.src == ''){
    that.src = 'default.gif';
}

而且,如前所述,错误消息可能是由于省略了要评估的 if 语句周围的括号引起的。

引用:
  • attr()
  • 关于jquery - 如果 $ ('img' ).attr ("src", ""),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10265144/

    10-12 12:46
    查看更多