0

OK、ページの 2 番目の div にマージンを設定したい

$('div#superid:nth-child(2)').css('margin-left', '10px');

すべてが機能し、目標を達成しました。しかし、このdivにスーパーチャイルドという名前の入力ラジオが少なくとも1つ含まれている場合にのみ、そのルールを適用したいと思います。したがって、上記のルールは次の場合に適用されます。

<div id="superid">
   <div>some text
   </div>
   <div>
    <input type="radio"  name="superchild" value="2010">
    <input type="radio"  name="superchild" value="2010">
   </div>
</div>

少なくとも 1 つの入力無線があるため、それname="superchild" を行う最善の方法は何ですか?

4

2 に答える 2

1
var div = $('div#superid:nth-child(2)');
if (div.find('input[name="superchild"]').length) {
    div.css('margin-left', '10px');
}
于 2012-11-22T13:28:35.230 に答える
1

You could also use the filter method. The script below selects every div in the #superid-div, which has at least one input field of type radio and name superchild. Then it adds the desired css to the selected divs.

$('div#superid > div').filter( function(index,elem) {
    return $(this).find('input[type=radio][name=superchild]').length > 0;
}).css('margin-left', '10px');

jsFiddle

If you want do add this style ONLY to the second div, use your selector instead. But I thought my script covers the desired behaviour better.

于 2012-11-22T13:29:47.873 に答える