1

こんにちは、次のような HTML があります。

<div id="music_interests">
    <ul class="interests">
        <li >
        <div class="interest inline">
        <img src=""/>
        <div class="interest_popup">
            1 users have this interest.
        <a href="http://localhost/love/index.php/my_profile/remove_interest/34" class="button red upper rounded_5 small remove">Remove interest</a>                                     </div>
            </div>
        </li>
    </ul>

ユーザーが削除ボタンをクリックしたら、親 div (この場合は music_interests) を選択する必要があります。どうすればそれについて行くでしょうか?

私は次のことを試しました、

$(this).parent().parent().parent().parent()もっとエレガントな方法はありますか?

さらに複雑なことに、削除ボタンはページの 4 つまたは 5 つの異なる領域で発生するため、アプリ内では実際には親 ID はありません。

4

3 に答える 3

5

あなたが使用する必要がありますclosest()

$(this).closest('div#music_interests');
//find the nearest div with id "music_interests"
//if i omitted the id, it retrieves the div with class "interest_popup"

またparents()

$(this).parents('div:eq(1)');
//get ALL the ancestor divs (until it reaches root tag)
//since music_interests is just 2 levels up, use :eq(1)
于 2012-04-21T09:30:04.840 に答える
0

削除ボタンが常に ul タグ (4 つまたは 5 つの異なる領域すべて) に存在する場合は、次のコードを使用できます。

$(this).closest("ul").parent()

この場合、ID を DIV タグに指定する必要さえありません。

于 2012-04-21T10:09:39.970 に答える
0

削除したい DIV の ID が静的である場合、IDセレクターは非常に高速な DOM 関数document.getElementsByIdに直接マップされるため、ID セレクターのみを使用する必要があります ( $("div#music_interests")のようなものではありません)。 :

$("#music_interests").remove();

ID が静的でない場合は、次のように UL を取得できます。

$(function(){ //execute when page has been loaded
    $(".remove").click(function(){ //attach click handler
        var removeDiv = $(this).closest("ul").parent().remove(); //get next UL -> DIV is its parent
        return false; //stop further processing of "click" event
    });       
});
于 2012-04-21T09:40:42.150 に答える