动态按钮ID-Javascript

时间:2019-03-11 20:42:46

标签: javascript loops button dynamic id

我有一些通过for循环生成的按钮,如下所示,并且id =:

<button type="submit" id = "like" class="btn btn-custom btn-sm like"><span id="tx-like">Like</span></button>

我有一个脚本,将“喜欢”更改为“不喜欢”,将“不喜欢”更改为“喜欢”,它通过ID获得元素:

$( function() {
        $('#like').click( function() {
            var t = $("#tx-like").html();
            if(t == 'Like'){
                $("#tx-like").html("Unlike");
            }else{
                $("#tx-like").html("Like");
            }
        } );
    } );

这仅在第一个按钮上起作用,因为它带有ID。如何使它在动态生成的所有按钮上起作用?

1 个答案:

答案 0 :(得分:1)

如上面的评论所述,您在同一页面中不应有多个ID。 您可以改用类,但是即使可以使用,也有一种更好的方法是使用data-attributes

// Retrieves all your elements using the `data-like` attribute.
const likes = document.querySelectorAll('[data-like]');

// For each element as `el`
likes.forEach(el => {
  el.addEventListener('click', () => {

    // Get its `data-like` value.
    const { like } = el.dataset;

    // If the value is 'false':
    if (like === 'false') {
      el.innerText = 'Dislike';
      el.dataset.like = 'true';
      return;
    }

    // Else...
    el.innerText = 'Like';
    el.dataset.like = 'false';
  });
});
/* You can easily customize your elements according to their current state. */

.like[data-like="true"] {
  border: solid 1px green;
}

.like[data-like="false"] {
  border: solid 1px red;
}
<!-- Remove duplicate IDs and use `data-like` instead. -->
<button type="submit" class="btn btn-custom btn-sm like" data-like="false">Like</button>
<button type="submit" class="btn btn-custom btn-sm like" data-like="false">Like</button>