我试图清除文本字段但它不起作用。我得到警报但它没有清除它。我做错了什么?
这是一个可在任何文本字段上调用的通用函数。
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function clearThis(target)
{
alert('before...' + target.value);
if ($(target).value == "Search ")
{
$(target).value = "set to something else";
$(target).style.color = '#000000';
$(target).style.fontStyle = 'italic';
}
else
{
$(target).value = "";
}
alert('after...' + target.value);
}
</script>
<title>My page</title>
</head>
<body>
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)"/>
</div>
</body>
</html>
答案 0 :(得分:1)
您对$
的使用表明您使用的是JQuery,但您不会在页面中包含该库。
如果您使用jQuery ,请使用正确的jQuery方式来获取和设置值(.val())和样式(.css())。当然,包括jQuery库......
function clearThis(target) {
alert('before...' + target.value);
if ($(target).val() == "Search ") {
$(target).val('set to something else');
$(target).css({'color':'#000000', 'font-style': 'italic'})
} else {
$(target).val('');
}
alert('after...' + target.value);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)" />
</div>
&#13;
事实上,如果您没有使用jQuery,则需要省略代码中的$()
语法。
function clearThis(target) {
alert('before...' + target.value);
if (target.value == "Search ") {
target.value = "set to something else";
target.style.color = '#000000';
target.style.fontStyle = 'italic';
} else {
target.value = "";
}
alert('after...' + target.value);
}
&#13;
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)" />
</div>
&#13;
答案 1 :(得分:0)
请检查以下代码
function clearThis(target)
{
// alert('before...' + target.value);
//alert(target);
if (target.value == "Search ")
{
target.value = "set to something else";
target.style.color = '#000000';
target.style.fontStyle = 'italic';
}
else
{
target.value = "";
}
//alert('after...' + target.value);
}
HTML代码
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)"/>
</div>
答案 2 :(得分:0)
首先需要在代码中更新两件事是你应该添加jquery.js文件,第二件是你想要更改值通过id或class。
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
function clearThis(target)
{
if (target.value == "Search ")
{
$("#username").val("set to something else");
}
else
{
$("#username").val('');
}
alert('after...' + target.value);
}
</script>
<title>My page</title>
</head>
<body>
<div class="historysearch">
<input id="username" type="text" value="Search " onclick="clearThis(this)"/>
</div>
</body>
</html>
答案 3 :(得分:0)
你做错了。
$(target)
是jquery对象,而不是js,因此无法访问value
你可以这样做(js):
target.value
或
像这样(jquery)
$(target).val()
答案 4 :(得分:0)
要使用JQuery清除文本框值,请使用以下行:
$(对照).VAL( “”);