选中输入复选框后发出警报 [英] Alert after checked input checkbox

查看:85
本文介绍了选中输入复选框后发出警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望在点击链接附加 html输入复选框后,在点击输入复选框后获取警告已选中

I want after click on link append html input checkbox in a class, after it when clicked on input checkbox getting alert is checked.

我尝试了以下代码但不适合我:

I tried as following code but dont work for me:

DEMO : http://jsfiddle.net/HsveE/

<a href="#" id="ho">Click Me</a>
<div class="hi"></div>



jQuery



jQuery

$('#ho').on('click', function(e){
    e.preventDefault();
    $('.hi').append('<input type="checkbox" id="isAgeSelected"/>');
})
$(".hi input[type=checkbox]").on('click',function () {
    alert('is checked')
})

如何修复它?

推荐答案

您需要委托,因为您的元素在绑定时不存在 - 或者在元素确实存在后绑定

You need to delegate since your element doesn't exist at the time of binding - or bind after element does exist

$(".hi").on('click',"input[type=checkbox]",function () {
    alert('is checked')
})

http://jsfiddle.net/5dYwG/

这样做使用class = hi将事件处理程序绑定到元素/元素 - 因为它在dom准备好时存在,并且是您要将复选框附加到的元素。然后它会监听事件,因为它会从你的复选框中冒出来并处理它们。

Doing this binds the event handler to your element/elements with class=hi - since it exists at the time the dom is ready and is the element you are appending your checkboxes to. It will then listen for the event as it bubbles up from your checkboxes and handle them.

另一件事是总是将你的绑定包装在document.ready函数中,所以它将等到你的dom加载后再尝试绑定事件处理程序。

One other thing is to always wrap your binding inside a document.ready function so it will wait until your dom is loaded before trying to bind the event handlers.

$(function(){
   // your binding code here
})

编辑

$(".hi").on('click',"input[type=checkbox]",function () {
  if(this.checked){
    alert('is checked')
  }
})

FIDDLE

这篇关于选中输入复选框后发出警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆