jquery中的多个类和id不在safari中工作

时间:2014-08-01 18:44:36

标签: javascript jquery

以下代码适用于firefox和chrome,但不适用于safari。有人能告诉我这是否是在jquery中添加多个类和id的正确方法?

jquery的

$(document).ready(function () {
$('.imgLink, .imgLink1, .imgLink2, .imgLink3, .imgLink4, .imgLink5, .imgLink6, 
.imgLink7, .imgLink8, .imgLink9').click(function () {
    var imgPath = $(this).attr('href');
    $('#theImage, #theImage1, #theImage2, #theImage3, #theImage4, #theImage5, #theImage6, 
#theImage7, #theImage8, #theImage9').attr('src', imgPath);
    return false;
  });
});

html for .imgLink

<a class="imgLink1" href="http://www.customtie.com/images/press/printwear-11-2013.jpg">Printwear Nov 2013</a>

hmtl for #theImage

<img id="theImage" src="http://www.customtie.com/images/press/counselor-2-2014.jpg" alt="" width="auto" height="auto">

2 个答案:

答案 0 :(得分:1)

呃...... 课程并不意味着以这种方式使用。更确切地说:

<a href="images/foo.jpg" data-targetid="1" class="imgLink">FOO</a>
<a href="images/bar.jpg" data-targetid="2" class="imgLink">BAR</a>

<img id="theImage1" src="images/default.jpg" alt="">
<img id="theImage2" src="images/default.jpg" alt="">

$(function () { // DOM ready shorthand

  $('.imgLink').click(function ( e ) {
       e.preventDefault();
       var imgPath = $(this).attr('href');
       var targetID = $(this).data('targetid');
       $('#theImage'+ targetID).attr('src', imgPath);
  });

});

|→jsBin demo

因此,基本上您将相同的类添加到所有可点击式广告,并添加一个data-*属性,其中包含您要定位的图像ID后缀的编号。

还有其他不错的方法(甚至更简单)来实现相同的目标,但没有看到一些HTML,这是盲目的猜测。

答案 1 :(得分:0)

我首先同意m90的建议,即你只想为所有这些元素添加一个类并选择它。

但我认为问题是你的字符串中途的回车。如果你想开始一个新的行,你必须结束第一行,然后将它们连接在一起,如下所示:

$('.imgLink, .imgLink1, .imgLink2, .imgLink3, .imgLink4, .imgLink5, .imgLink6,'+ 
  '.imgLink7, .imgLink8, .imgLink9').click(function () {
    var imgPath = $(this).attr('href');
    $('#theImage, #theImage1, #theImage2, #theImage3, #theImage4, #theImage5, #theImage6, ' +
      '#theImage7, #theImage8, #theImage9').attr('src', imgPath);
    return false;
});