簡體   English   中英

jQuery最近的類選擇

[英]JQuery Closest Class Select

我的布局如下(簡化)

<div>
    <div class="msgOutput" id="msg2"></div>
    <form>
        <table>
            <tbody>
                <tr>
                    <td>
                        <p><input type="file" class="documentFile" id="documentFile2" /></p>
                    </td>
                </tr>
                ... more code here ...
            </tbody>
        </table>
    </form>
</div>

我想把東西在div.msgOutputinput.documentFile變化(有在頁面上的多個副本)

還有更多代碼,因此我確實需要搜索最接近的class="msgOutput"

我知道這與closest()parent()東西有關,但不起作用:/

到目前為止,我已經嘗試過類似的事情:

$('.documentFile').change(function(e){
    ....
    $($(this).attr('id')).parent().children('.msgOutput').attr('id').append('Hello World');
    $(this).closest('div').find('.msgOutput').append('Hello World');
    $(this).closest('div').sibling('.msgOutput').append('Hello World');
    ....
});

但這不起作用:(。任何人有任何想法嗎?

我會推薦這樣的東西: http : //jsfiddle.net/cr94dtk0/

您應該在包含的div周圍放置一個類或id,以便可以進行DOM遍歷

<div class="container">
<div class="msgOutput" id="msg2">hi</div>
<form>
    <table>
        <tbody>
            <tr>
                <td>
                    <p><input type="file" class="documentFile" id="documentFile2" /></p>
                </td>
            </tr>
        </tbody>
    </table>
</form>

  $(".documentFile").change(function(){
  $(this).closest(".container").find(".msgOutput").text("TEXT GOES HERE");
});

您已經找到了最接近的div,但是要添加額外的選擇器方法,這會使您的結果更加混亂。

這有效:

$(this).closest('div').append('Hello World'); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM