无法更改动态添加的元素的属性

时间:2018-11-13 17:12:03

标签: javascript jquery

我正在研究以下演示。为什么我不能在这里的弹出框中更改隐藏元素#prev的css规则?

$("[data-toggle=popover]").each(function(i, obj) {

$(this).popover({
  html: true,
  content: function() {
    var id = $(this).attr('id')
    return $('#popover-content-' + id).html();
  }
});

});

$(document).on("click","#next", function(){
    console.log('Click on Next is working but the #prev is not displaying!');
   $("#prev").css('display','block');
});
#prev{
   display:none;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

<div class="container">
    <a data-toggle="popover" data-container="body" data-placement="right" type="button" class="btn btn-secondary" data-html="true" href="#" id="login">Display</a>
    <div id="popover-content-login" class="d-none">
        <button id="next"> Next</button>
        <button id="prev"> Prev</button>
    </div>
</div>

1 个答案:

答案 0 :(得分:2)

问题在于,由于move $t0, $a0 # COPY $A0 TO $T0 库通过克隆HTML的工作方式,您正在页面中复制相同的popover()。通过该id选择时,它仅读取找到的第一个,而不是可见的。要解决此问题,请使用DOM遍历找到相对于单击的id的{​​{1}},并将.prev属性更改为.next。试试这个:

id
class
$("[data-toggle=popover]").each(function(i, obj) {
  $(this).popover({
    html: true,
    content: function() {
      var id = $(this).attr('id')
      return $('#popover-content-' + id).html();
    }
  });
});

$(document).on("click", ".next", function() {
  $(this).next(".prev").show();
});