jQuery prepend()不起作用,怎么了



我很困惑我的append()没有出现在HTML中。你们能告诉我以下代码出了什么问题吗:

<div class="form-group" id="password">
     <label class="control-label" for="inputError"> Password:</label>
     <input type="password" class="form-control" id="input-password" placeholder="Password" value="" name="password"/>
</div>

我的js:

<script type="text/javascript">
        $('input[name="password"]').focusout(function() {
            if($(this).val()==""){
                $('#password').attr('class','form-group has-error');
                $('#password .control-label').prepend("<span class='fa fa-times-circle-o'></span>");
                $('#password .control-label').text(' Input your new password!');
            }
        });
</script>

假设focusout事件被触发,问题是您在.prepend()之后使用.text(),这将删除添加了.prepend()的内容

$('input[name="password"]').focusout(function () {
    if ($(this).val() == "") {
        $('#password').attr('class', 'form-group has-error');
        $('#password .control-label').text(' Input your new password!');
        $('#password .control-label').prepend("<span class='fa fa-times-circle-o'></span>");
    }
});

演示:Fiddle


所以

jQuery(function($){
    $('input[name="password"]').focusout(function () {
        if ($(this).val() == "") {
            $('#password').attr('class', 'form-group has-error');
            $('#password .control-label').text(' Input your new password!').prepend("<span class='fa fa-times-circle-o'></span>");
            //$('#password .control-label').html('<span class="fa fa-times-circle-o"></span> Input your new password!');
        }
    });
});

相关内容

最新更新