在jQuery中链接时CSS属性不起作用

CSS property not working when chaining in jQuery

本文关键字:CSS 属性 不起作用 链接 jQuery      更新时间:2023-09-26

这是jQuery代码:

$("#web").hover(
  function () {
    $(this).css({
             'background-color': '#ecf5fb',
             'cursor': 'pointer',
             'border': '1px solid #378ac4'
           })
           .children("a").children("img").attr("src", "1.png")
           .end().children("p").css("opacity", "1.0");
           $('#commentweb').stop(true, true).fadeIn();
  }, 
  function () {
    $(this).css({
             'background-color': '#e8e3e3',
             'border': '1px solid grey'
             })
             .children("a").children("img").attr("src", "2.png")
             .end().children("p").css("opacity", "0.5");
             $('#commentweb').stop(true, true).fadeOut();
  }
);

问题是不透明度没有改变,而其他一切都有效。但是如果我写而不是这个代码

$(this).css({
         'background-color': '#ecf5fb',
     'cursor': 'pointer',
     'border': '1px solid #378ac4'
       })
       .children("a").children("img").attr("src", "1.png");
$(this).children("p").css("opacity", "1.0");

它是有效的。为什么会发生这种情况?

这是小提琴:http://jsfiddle.net/mMB3F/6/

如果要返回到原始选择,则必须调用.end()两次,就像调用链上的子级两次一样。

$("#web").hover(
  function () {
    $(this).css({
             'background-color': '#ecf5fb',
             'cursor': 'pointer',
             'border': '1px solid #378ac4'
           })
           .children("a").children("img").attr("src", "1.png")
           .end().end().children("p").css("opacity", "1.0");
           $('#commentweb').stop(true, true).fadeIn();
  }, 
  function () {
    $(this).css({
             'background-color': '#e8e3e3',
             'border': '1px solid grey'
             })
             .children("a").children("img").attr("src", "2.png")
             .end().end().children("p").css("opacity", "0.5");
             $('#commentweb').stop(true, true).fadeOut();
  }
);

http://jsfiddle.net/mMB3F/8/

如果你想回到原始的jquery对象,你需要在其中添加一个额外的.end()-每个过滤操作都会在堆栈上放置一个新的jquery对象-每个对.end的调用都会从堆栈中"弹出"最后一个。这是一个更新的小提琴:http://jsfiddle.net/mMB3F/7/