图像onclick事件无法正常工作

时间:2012-04-30 09:16:19

标签: image onclick jquery

我试着为我的图片制作一个onclick事件,但它没有工作......警报没有出现..

$(document).ready(function(){
    $('img.closeAttrIcon').click(function(){
        alert("ww");
    });
});

即使我尝试使用..绑定..没有希望......

$(document).ready(function(){
    $('img.closeAttrIcon').bind('click',function(){
        alert("ww");
    });
});

将在此活动期间创建html:

$('a#btnAddStdntAttr').click(function(){
    var newAttr = '<div class="attrParent"><br class="clear"><label></label><input type="text" id="stdntAttributeKey1" maxlength="250" style="width: 13%;" name="stdntAttributeKey1"/>';
    newAttr+= '<input type="text" id="stdntAttributeValue1" maxlength="250" style="width: 13%;" name="stdntAttributeValue1"/>';
    newAttr+= '<img src="<c:url value="/static/images/closeIcon.png"/>" onclick="removeStdntAttr();" class="closeAttrIcon" alt="Close" title="Close" /></div>';
    $(this).after(newAttr);
});

我在这里做错了什么..请帮助..

1 个答案:

答案 0 :(得分:0)

它不起作用,因为你是在第一次创建DOM之后注入它,因为你需要使用live(如果使用直到jQuery 1.7)或on如果使用( 1.7+)绑定方法

将您的电话改为:

$(function(){
   $('img.closeAttrIcon').live('click', function() {
        alert("ww");
    });
});

如果你正在使用jQuery 1.7+,那么你也可以这样做:

$(document).on('click', 'img.closeAttrIcon', function() {
    alert("ww");
});