简体   繁体   English

使用jquery多次对同一个id执行click功能

[英]Perform click function on same id at more than once using jquery

NOTE: Sorry for Asking this type of question. 注意:抱歉提出此类问题。

I have a form with save button on top and bottom. 我有一个顶部和底部带有保存按钮的表单。 I make it as common id to perform the click function. 我将它作为执行点击功能的通用ID。 For the first save button get the alert but for second save button contain same id only but the alert won't appear. 对于第一个保存按钮,获取警报但第二个保存按钮仅包含相同的ID,但不会显示警报。 I am not sure how to make the alert for the two button which contain same id. 我不知道如何为包含相同ID的两个按钮发出警报。

  jQuery("#preview").click(function() {
            alert("Handler for .click() called.");
        });

Here is the fiddle. 这是小提琴。 http://jsfiddle.net/N8Mhd/ http://jsfiddle.net/N8Mhd/

Any suggestion would be great. 任何建议都会很棒。

IDs should be unique, do not use the same id for two elements. ID应该是唯一的,不要对两个元素使用相同的id。 Use classes instead. 请改用类。

So just use 所以只需使用

<input type="button" class="preview" value="Click Me :)"/>
<input type="button" class="preview" value="Click Me :)"/>

jQuery(".preview").click(function() {
    alert("Ponies!");
});

As Id can not be duplication so you can change the Id selector to class selector and then can bind the same event. 由于Id不能重复,因此您可以将Id选择器更改为class选择器,然后可以绑定相同的事件。

<input type="button" class="preview" value="Click Me :)"/>    
<input type="button" class="preview" value="Click Me :)"/>

Script: 脚本:

jQuery(".preview").click(function() {
    alert("Handler for .click() called.");
});

jsFiddle Demo jsFiddle演示

You can't use two elements with same id, ids need to be unique. 您不能使用具有相同ID的两个元素,ID必须是唯一的。 You should use classes: 你应该使用类:

<input type="button" class="preview" value="Click Me :)"/>

...

<input type="button" class="preview" value="Click Me :)"/>


<script>
jQuery(".preview").click(function() {
   alert("Handler for .click() called.");
});
</script>

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

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