jQuery更新后使用当前数据

时间:2018-09-26 10:50:40

标签: javascript jquery html

我正在尝试获取指定seat的当前状态,因此每个席位开头都具有状态free,并且该状态将更改为'man', 'women'或{{1 }}。

因此,我选择了其中一种状态后,例如:'child'free! 我想提醒Ive更新的座椅当前状态,它向我显示了旧状态man,而不是free!这是代码:

我不能使用man函数,因为我添加内容的方式不是单击click().man, .woman,所以我必须使用.child

on()
$(document).on("click", ".man, .women, .child", function() {
        var seatNumberHere = $(this).data("seat-number"); //Number of seat
        var seatPerson = $(this).data("person"); //Displays 'men', 'women' or 'child'

        $("[data-the-seat='" + seatNumberHere + "']").attr("data-status", seatPerson); //Updates the attribute data-status="free" to "men"
        alert($("[data-the-seat='" + seatNumberHere + "']").data("status")); //Here is the problem it shows still "free"
      });

1 个答案:

答案 0 :(得分:2)

这里获取的数据将停留在最后访问的值上,因为仅在DOM中更改了最后一个值

请注意

  • .attr()更改此元素的DOM值 和
  • .data()将更改某个内存中的元素值

那么两件事

为了获得相同的值,dom(attr)或内存  (数据),您应该将两者都设置为

请参见以下代码段:

$(document).on("click", ".man, .women, .child", function() {
    console.log(this);
    var seatNumberHere = $(this).data("seat-number"); //Number of seat
    var seatPerson = $(this).data("person"); //Displays 'men', 'women' or 'child'
    
    
    $("[data-the-seat='" + seatNumberHere + "']").attr("data-status", seatPerson);
    $("[data-the-seat='" + seatNumberHere + "']").data("status", seatPerson);
    //Updates the attribute data-status="free" to "men"
    
    alert("value of attr :"+$("[data-the-seat='" + seatNumberHere + "']").attr("data-status"));
    alert("value of data :"+$("[data-the-seat='" + seatNumberHere + "']").data("status")); //Here is the problem it shows still "free"
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="seat"
      style="top: 10px; left: 130px;"
      data-the-seat="1"
      data-status="free"
      data-toggle="popover"
      data-html="true"
      data-placement="top">
      <div class='man' data-person='man' data-seat-number='1'>M</div><div class='women' data-person='women' data-seat-number='1'>W</div><div class='child' data-person='child' data-seat-number='1'>C</div>"
      1
    </div>