-1

I've got this jQuery event code to handle clicking on the whole document, any link, button and textfield.

        <script>

            $(document).ready(function() {
                //whole document
                $('html').dblclick(function() {
                    alert('ouch!');
                });

                //any link
                $('a').mouseover(function(){
                    var message = "<p>You pointed a link!</p>";
                    $('.main').append(message);
                });

                //only one button ?                 
                $('#button').click(function(){
                    $(this).val("Stop it!");
                });

                //text field, I suppose it would have the same problem
                //as button                 
                $('#textfield').focus(function() {
                    $(this).css('background-color', '#F59898');
                }); 
            });

        </script>

and this HTML form code:

        <form action="#" method="get">
            <fieldset>
                <legend>A Form</legend>

                <p>
                  <input name="button" type="button" id="button" value="A Button" />
                </p>

                <p>
                    <input name="textfield" type="text" id="textfield" />
                </p>

                <p>
                  <input type="button" id="button" value="Doesn't work"/>
                </p>

            </fieldset>
        </form>

I cannot understand the part where the user clicks the button and it changes its value. For a single button it works fine, but when I add a second with same ID (#button), it still works only for the first one. I expected this to run with any button which I have assigned that ID. I hope I made ​​myself clear.

4

1 回答 1

3

不能有多个具有相同 ID 的元素。您可以像这样更改代码,

$('input[type=button]').click(function(){
    $(this).val("Stop it!");
});

这将应用页面中的所有输入按钮

于 2013-07-05T16:46:46.233 回答