开发者

Why won't this jQuery one-liner do what it is supposed to?

I'm working on some form UI coding and wrote this jQuery one-liner:

$('input[type=text]开发者_运维百科').val($(this).attr('default-value'));

Intention is to give every input text field its default value which is supplied within an attribute.

Any suggestions? TIA


$('input[type=text]').each(function () {
    $(this).val($(this).attr('default-value'));
});

this inside your val() call isn't referencing the element, but it's simply the context of the function where you're running this one-liner.

Also, when defining custom attributes, you might consider investing in HTML5 earlier on and use the "data-*" convention: In HTML5 it is legal to define custom attributes as long as they are prefixed with "data-". So, I would use something like "data-default" instead of "default-value".


Try:

$('input[type=text]').each(function() {
   $(this).val($(this).attr('default-value'));
});

The problem with yours is that $(this) wasn't defined in the context you were using it in.


It isn't working because the context of this isn't what you'd expect. Try this:

$('input[type=text]').each(function(){
    var $this = $(this);
    $this.val($this.attr('default-value'));
});


I think you want:

$('input[type=text]').val(function(i,e) { return $(e).attr('default-value'); } );


Because you aren't referencing the element correctly...

You are immediately assigning the val of the input to the current scope of $(this) instead of the element you are getting.

$(":text").each(function() { $(this).val($(this).attr('default-value')); });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜