我想知道是否有 jQuery 专家愿意将下面的脚本转换为 jQuery。我自己转换它时遇到问题,更愿意使用 jQuery 等价物。
我想做的是简单地从提交时的关键字字段中删除“搜索”的默认值,因为用户可以将关键字字段留空。
function clearValue() {
var searchValue = document.getElementById("global-search").value;
if (searchValue == "Search") {
document.getElementById("global-search").value = "";
}
}
如有任何帮助,我们将不胜感激。
最佳答案
//wait for the DOM to be ready (basically make sure the form is available)
$(function () {
//bind a `submit` event handler to all `form` elements
//you can specify an ID with `#some-id` or a class with `.some-class` if you want to only bind to a/some form(s)
$('form').on('submit', function () {
//cache the `#global-search` element
var $search = $('#global-search');
//see if the `#global-search` element's value is equal to 'Search', if so then set it to a blank string
if ($search.val() == 'Search') {
$search.val('');
}
});
});
请注意 .on()
是 jQuery 1.7 中的新内容,在本例中与 .bind()
相同。
这是与此答案相关的文档:
.on()
:http://api.jquery.com/on.val()
: http://api.jquery.com/valdocument.ready
:http://api.jquery.com/ready/- jQuery 选择器:http://api.jquery.com/category/selectors/
关于javascript - Convert JS function to jQuery - (输入字段清除默认值),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9186402/