简体   繁体   English

动态按钮 ID - Javascript

[英]Dynamic button Ids - Javascript

I have a number of buttons generated from a for loop as follows and the id = like:我有许多从 for 循环生成的按钮,如下所示,id = 像:

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

I have a script that changes the "like" to "unlike" and "unlike" to "like", it gets element by Id:我有一个脚本将“like”更改为“unlike”并将“unlike”更改为“like”,它通过Id获取元素:

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

This is only functional on the first button since it taking the id.这仅在第一个按钮上起作用,因为它采用了 id。 How I can get it functional on all buttons that are generated dynamically?如何让它在动态生成的所有按钮上发挥作用?

As said in comments above, you should not have multiple IDs in the same page.正如上面的评论中所说,您不应该在同一页面中有多个 ID。 You could use classes instead, but even if it would work, there is a better approach which is to use data-attributes .您可以改用类,但即使它可以工作,也有更好的方法,即使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM