问题
Has anyone successfully added jQuery placeholder text for IE8 to dynamically created form elements.
For example, I click a button and a form appears that is loaded through AJAX, I need to hit the new form with placeholder text.
I have tried using jQuery .live, .bind, .on etc... but neither are catching the new elements when they are created.
I've also tried placing it in a click function so that when they click the button the placeholder function is activated.
$('input[placeholder]').on("focus", function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
$(this).find('input[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
回答1:
$(document).on({
focus: function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
},
blur: function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}
},"input[placeholder]");
$(document).on("submit","form",function() {
$(this).find('input[placeholder]').each(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
});
});
$('input[placeholder]').blur();
Let me know if this refactoring works.
来源:https://stackoverflow.com/questions/13163872/adding-jquery-placeholders-to-dynamically-created-form-elements