简体   繁体   中英

How to recognize which button is clicked

I am using wordpress for my blog posts - all posts are fetched on the same page and each post has button, I need to be able to recognise which button of which post was clicked.

I can do it only with hardcoded data, but I am unsuccessful with dynamic ones.

I tried to give a trigger button common class and then detect it in JS.

<div class="row"> 
     <button class="common-button-class">CLICK</button>
</div>

let openButton = document.getElementsByClassName(
    'common-button-class'
);


if (openButton != null) {
            document.querySelector('.common-button-class')
            .addEventListener('click', (event) => {
            // tried detect event id here unsuccessfully 
});
   }

Is there function of how to know which post is being triggered?

you can use jquery in WordPress

first add properties just like data-id and keep post id in it. then:

 $(document).on("click",".common-button-class", function () {
     var clickedBtnID = $(this).data('id'); 
     alert('you clicked on button #' + clickedBtnID);
 });

Use querySelector instaid of getElementsByClassName

let openButton = document.querySelector('.common-button-class');
openButton.onclick = function() {
    //Your code here
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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