开发者

jQuery <input> element problem with onclick attribute

I want an element with an onclick attribute. When I use jQuery, it doesn't seem to wo开发者_StackOverflow社区rk. Here is my code:

$("h1").append($("<input>", {type: "text", onclick: "alert();"}));

The following code does work:

<input type="text" onclick="alert();"></input>


Why not:

$("h1").append($("<input>").attr("type","text").click(function(){alert()}));


you really don't want the onclick attribute, you want to use jQuery's click event. Setting the onclick attribute works in most browsers, but it wouldn't be taking advantage of jQuery's normalized events and cross-browser support.

Also, you're not using the jQuery factory method correctly, the second argument it takes is the context for the selector, or, in the case where you're creating html, the owner document for the element to be created in. You really should spend some time reading through the api.

You can chain most methods in jQuery, so the "jQuery way" of doing what you want is:

$('<input>').attr('type', 'text').click(function(){alert();}).appendTo('h1');


How about something like:

$('h1').append('<input type="text">').find('input').live('click', function () {
    alert('bam');
});

EDIT: Yeah I noticed that David Thomas' comment was correct, just changing the alert to actually output something works fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜