简体   繁体   中英

onclick event on List of buttons is not working using JQuery

I am trying to add events on my buttons inside a list, but it appears that only the first button on the list is being registered with an onclick event. There are no errors shown, but I don't get why only the first part of the button is being registered with an event? Here it is:

<ul id = "button-list"> 
    <li>
        <button class = "buttons" id = "first"  name = "ltrContainer"   ></button>
    </li>
    <li>
        <button class = "buttons" id = "second" name = "ltrContainer"  ></button>
    </li>
    <li>
        <button class = "buttons" id = "third"  name = "ltrContainer"   ></button>
    </li>
    <li>
        <button class = "buttons" id = "fourth" name = "ltrContainer"  ></button>
    </li>
    <li>
        <button class = "buttons" id = "fifth" name = "ltrContainer"  ></button>
    </li>
    <li>
        <button class = "buttons" id = "sixth" name = "ltrContainer"   ></button>
    </li>
</ul>

only the first button is being registered with an event and here is my JQuery code

$('.buttons').click(function(){
    textContainer.value += this.innerHTML;
    alert(this.innerHTML);
});

Thery are no value in inner html of buttons. you will write any value in buttons. I have modify your code check it

<ul id = "button-list"> 
    <li>
        <button class = "buttons" id = "first"  name = "ltrContainer"   >1</button>
    </li>
    <li>
        <button class = "buttons" id = "second" name = "ltrContainer"  >2</button>
    </li>
    <li>
        <button class = "buttons" id = "third"  name = "ltrContainer"   >3</button>
    </li>
    <li>
        <button class = "buttons" id = "fourth" name = "ltrContainer"  >4</button>
    </li>
    <li>
        <button class = "buttons" id = "fifth" name = "ltrContainer"  >5</button>
    </li>
    <li>
        <button class = "buttons" id = "sixth" name = "ltrContainer"   >6</button>
    </li>
</ul>



$(document).ready(function()
{   
    $('.buttons').click(function(){
    document.getElementById('textContainer').value += this.innerHTML;
    alert(this.innerHTML);
    });
});
 $(function(){
    $('.buttons"').click(function(){
            var myValue = $(this).html();
            alert(myValue); 
        });
      });
 });

I hop this will help

$("#button-list .buttons").each(function () {
            $(this).bind("click", function() {
                //Put your code here
            });
});

Hope this helps...

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