如果点击的img src包含特定文本

6

大家好,我该如何检查所点击的图像(img)标签的src属性中是否包含特定文本,如果存在,则执行一些功能?

示例:

<img src="file:///C:/path/img4-dog.jpg">, <img src="file:///C:/path/img4-cat.jpg">

如果所点击的图像(img)标签的src属性中包含'dog'等文本,则运行警报提示。

5个回答

10
$('img').click(function(){
   if (this.src.indexOf("dog") != -1) 
      alert('contains dog');
})

7
$('img').click(function(e) {

    if ($(this).attr('src').indexOf('dog') != -1) {
        alert('this contains dog');
    } 

});

3

试试这个

$('img').click(function(){
   if($(this).attr('src').toLowerCase().indexOf("dog") >= 0){
       alert('text found');
     }
});

2
$('img').click(function(){
    if($(this).attr('src').indexOf('img4-dog') >= 0) alert('found');
});

1
$('img').on('click', function() {
    var imgsrc = $(this).attr('src');
   // Use a regular expression to find a match
    var test = imgsrc.search(/dog/);
    if (test > -1) {
      // do something
    }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接