JQuery siblings.data()没有返回正确的值

时间:2017-09-26 14:59:37

标签: javascript jquery html asp.net-mvc-4

我有一个类似的Html:

<div class="ajouterContainer" id="ajouterContainer1">
    <div class="ajouter ajoutersaved" id="ajouter1" data-no="1" style='background-image: url(..."); background-color: rgb(255, 0, 0);' >
        <div class="pieceModifierContainer"></div>
        <a onclick="return false;" href="#">
            <label>INCLUSION</label>
        </a>
        <span class="pieceFileName">INC-00001_41-H.png</span>
    </div>
    <span class="submenuOpener opened" id="smo1" style="background-color: rgb(255, 0, 0);">▼<input type="hidden"></span>
</div>

我尝试在ajouterContainer div的click事件中获取ajouter1的data-no属性:

$(".ajouterContainer").on("click", function(event) {
    var itemID = $(event.target).attr('id');
    var itemNumber = itemID.substring(itemID.length - 1);
    var idToFind = "#smo" + itemNumber;
    var openerItem = $(event.target).find(idToFind);
    if (!openerItem.length) {
        $(event.target).css("background-color", "red");
        return;
    }
    //the data-no attribute is 3 by default. I change it using jQuery to 1.
    var dataNo = openerItem.siblings().data("no"); //returns 3
    $(openerItem).prev().attr("data-no"); // returns 1 (the correct value).

});

openerItem.siblings().data("no");有什么问题? 在通过代码更改它之前,它可以工作。

1 个答案:

答案 0 :(得分:1)

您应该使用$(openerItem).siblings('[data-no]').data('no')

过滤您的兄弟姐妹

编辑:

问题不在于兄弟姐妹()方法;它是因为您使用了event.target来获取实际点击的子元素,而不是ajouterContainer1。我已将this替换为适合您的$(".ajouterContainer").on("click", function(event) { var itemID = this.id; var itemNumber = itemID.substring(itemID.length - 1); var idToFind = "#smo" + itemNumber; var openerItem = $(this).find(idToFind); if (!openerItem.length) { $(event.target).css("background-color", "red"); return; } //the data-no attribute is 3 by default. I change it using jQuery to 1. var dataNo = openerItem.siblings().data("no"); //returns 3 console.log(dataNo); });。我希望这会有所帮助:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ajouterContainer" id="ajouterContainer1">
    <div class="ajouter ajoutersaved" id="ajouter1" data-no="1" style='background-image: url(..."); background-color: rgb(255, 0, 0);' >
        <div class="pieceModifierContainer"></div>
        <a onclick="return false;" href="#">
            <label>INCLUSION</label>
        </a>
        <span class="pieceFileName">INC-00001_41-H.png</span>
    </div>
    <span class="submenuOpener opened" id="smo1" style="background-color: rgb(255, 0, 0);">▼<input type="hidden"></span>
</div>
&#13;
{{1}}
&#13;
&#13;
&#13;