开发者

.live() and .data()

开发者 https://www.devze.com 2023-03-26 11:34 出处:网络
I\'m trying to make a piece of JavaScript that allows me to just add an <input> with a certain class, and it will automatically add placeholder-li开发者_StackOverflow中文版ke behaviour to it. Th

I'm trying to make a piece of JavaScript that allows me to just add an <input> with a certain class, and it will automatically add placeholder-li开发者_StackOverflow中文版ke behaviour to it. The problem is, I load some inputs in via AJAX. I use the .live() method to get around this, however .data() doesn't want to play.

Here's an example:

jQuery

$(".placeHolder").data("originalValue", $(this).val());

$(".placeHolder").live("focus", function() {
    if($(this).val() == $(this).data("originalValue"))
    {
        $(this).val('');
    }
});
$(".placeHolder").live("blur", function() {
    if(!$(this).val().length)
    {
        $(this).val($(this).data("originalValue"));
    }
});

// Load inputs into an element
$("selector").load("loadInput.php", function(response, status, xhr) {
    $(".placeHolder").data("originalValue", $(this).val());
});

HTML

<input type="text" name="foo" value="Bar" class="placeHolder">

The problem is the fact that the <input>'s original value isn't stored by .data() anywhere - even in the .post() call. There can be more than one .placeHolder on the page.

Am I using .data() incorrectly? If not, what else is going wrong?


@JAAulde has a point...

$(".placeHolder").data("originalValue", $(this).val());

Should be this maybe?

$(".placeHolder").each(function(){
  $(this).data("originalValue", $(this).val());
});


.live() places an event handler on the document element, which uses event bubbling to catch events, and checks if they come from an appropriate source. .data() attaches data to an existing element. You're using live() because you load your data via AJAX, and it will work regardless of when your <input> elements appear. But data() doesn't work that way.

If you are using a recent enough version of jQuery, you may be able to use HTML5 data- attributes and access them using the data() handler.

0

精彩评论

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