我如何添加一个单一的HTML文件

时间:2013-06-28 09:13:14

标签: javascript html javascript-events

我想在一个html中绑定下面的脚本和表单代码我该怎么办? 我认为当没有任何内容显示时,这段代码会给我一个空白值?

<form method="post" action="contactengine.php">
    <input type="textbox" class="default-value" name="Name" id="Name" value="Full Name">

    <input type="textbox" class="default-value" name="Email" id="Email" value="Email">

    <input type="submit" name="submit" id="submit" value="Submit" class="submit-button" />
</form> 

$('.default-value').each(function() {
    var default_value = $(this).val();
    $(this).css('color', '#746F66'); // this could be in the style sheet instead
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
            $(this).css('color', 'black');
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            $(this).css('color', '#746F66');
            this.value = default_value;
        }
    });
});

2 个答案:

答案 0 :(得分:4)

你可以试试这个: -

<script type="text/javascript">
 $(function(){
 $('.default-value').each(function() {
var default_value = $(this).val();
$(this).css('color', '#746F66'); // this could be in the style sheet instead
$(this).focus(function() {
    if(this.value == default_value) {
        this.value = '';
        $(this).css('color', 'black');
    }
});
  $(this).blur(function() {
    if(this.value == '') {
        $(this).css('color', '#746F66');
        this.value = default_value;
    }
  });
});
});
 </script>
<body>
<form method="post" action="contactengine.php">
<input type="textbox" class="default-value" name="Name" id="Name" value="Full Name">

<input type="textbox" class="default-value" name="Email" id="Email" value="Email">

<input type="submit" name="submit" id="submit" value="Submit" class="submit-button" />
</form>
</body> 

答案 1 :(得分:2)

在HTML文件的末尾添加此代码段。

<script type="text/javascript">
$(function(){

$('.default-value').each(function() {
    var default_value = $(this).val();
    $(this).css('color', '#746F66'); // this could be in the style sheet instead
    $(this).focus(function() {
        if(this.value == default_value) {
            this.value = '';
            $(this).css('color', 'black');
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            $(this).css('color', '#746F66');
            this.value = default_value;
        }
    });
});

});
</script>