使用jquery检测动态按钮

时间:2013-09-27 08:06:30

标签: jquery asp.net-mvc

我的视图下面有一些按钮。这是通过服务器端代码动态生成的。所以我的问题是我需要编写通用的jquery点击事件来完成该按钮的相关任务。 (这里我有所有按钮的通用方法作为服务器代码)。那么如何检测特定按钮来写我的通用服务器调用?

注意:所有按钮的常见部分是预付费套餐

 <button id="pre-paid-package-12-day-camp" class="actionButton pre-paid-package-12-day-camp " name="key" value="pre-paid-package-12-day-camp" type="submit">
      Apply 12-Day Camp package
   </button>
<button id="pre-paid-package-20-day-camp" class="actionButton pre-paid-package-20-day-camp " name="key" value="pre-paid-package-20-day-camp" type="submit">
      Apply 20-Day Camp package
   </button>

2 个答案:

答案 0 :(得分:3)

您可以执行以下操作

Html

    <button id="pre-paid-package-12-day-camp" class="actionButton pre-paid-package-12-day-camp " name="key" value="pre-paid-package-12-day-camp" type="submit">Apply 12-Day Camp package</button>
    <button id="pre-paid-package-20-day-camp" class="actionButton pre-paid-package-20-day-camp " name="key" value="pre-paid-package-20-day-camp" type="submit">Apply 20-Day Camp package</button>

Th JS

$(document).on('click', '[id^="pre-paid-package"]', function() {
    alert('clicked');
});

JsFiddle

修改 根据安东的建议,我已经更新了我的答案

答案 1 :(得分:1)

您可以使用.on()jquery attribute selctor

$("button[id^='pre-paid-package']").on('click', function(){
   // code here
});

此处^适用于以

开头