Adding jQuery placeholders to dynamically created

2019-08-20 10:17发布

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条回答
贪生不怕死
2楼-- · 2019-08-20 10:54
$(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.

查看更多
登录 后发表回答