jQuery prepend()不工作,有什么不对

时间:2014-08-28 11:28:48

标签: javascript jquery

我很困惑我的追加()没有出现在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>

1 个答案:

答案 0 :(得分:3)

假设触发了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!');
        }
    });
});