jquery 中的 end() 方法可以工作,但表现出奇怪的行为



下面是HTML代码

<div id="Parent">
            This is Parent Div
             <p> This is first child.</p>
             <p> This is second child.</p>
             <p> This is Third child.</p>
        </div>
<input type="button" id="clickme" value ="click me" />

这是jQuery代码

$('#clickme').click(function() {
    $('#Parent')
    .children() // 1st phase action on children begins here
    .css('color', 'blue')
    .end() //Here 1st phase action on children ends 
    .css({
        'color': 'red',
        'border-color': 'blue',
        'border-width': '3px',
        'border-style': 'solid'
    }) // Here 1st phase action on Parent completed
   .children() //2nd phase action on children begins
   .css({
        'border-color': 'red',
        'border-width': '2px',
        'border-style': 'solid'
    }).end() // 2nd phase action on children ends
    .css('font-style', 'italic'); //2nd phase action on parent begin/ends
});​

在上面的jquery代码中,我正在尝试将不同的样式应用于孩子和父母。 除了斜体样式外,一切都很好。 谁能解释为什么会发生这种奇怪的事情。

抱歉错过了这个 - 我正在将斜体应用于父母,但孩子们也会改变。 如何预防?

在父级和子级之间来回弹跳以设置不同的 css 毫无意义。

只需组合父级的 css 属性和子项的属性,并且只为每个属性进行一次 css 调用。它消除了使用end()的混乱,并且更有效,更易于阅读。

$('#clickme').click(function() {
    $('#Parent')   
    .css({
        'font-style': 'italic',
        'color': 'red',
        'border-color': 'blue',
        'border-width': '3px',
        'border-style': 'solid'
    })
   .children()
   .css({
       'color':'blue',
        'border-color': 'red',
        'border-width': '2px',
        'border-style': 'solid'
    })
});

演示:http://jsfiddle.net/T9zBS/

我怀疑您只期望在父级中的文本上使用斜体,在这种情况下,现在很明显您还需要将子字体设置为普通字体。

最新更新