Javascript 将JS函数转换为jQuery-(输入字段清除默认值)

Javascript 将JS函数转换为jQuery-(输入字段清除默认值),javascript,jquery,forms,onsubmit,Javascript,Jquery,Forms,Onsubmit,我想知道是否有jQuery专家愿意将下面的脚本转换为jQuery。我自己在转换它时遇到了困难,我更喜欢使用jQuery等价物 我试图做的只是从Submit上的关键字字段中删除默认值“Search”,因为用户可以将关键字字段留空 function clearValue() { var searchValue = document.getElementById("global-search").value; if (searchValue == "Search") {

我想知道是否有jQuery专家愿意将下面的脚本转换为jQuery。我自己在转换它时遇到了困难,我更喜欢使用jQuery等价物

我试图做的只是从Submit上的关键字字段中删除默认值“Search”,因为用户可以将关键字字段留空

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()
  • .val()
  • 文档准备就绪
  • jQuery选择器:

哇。。。那很快。谢谢大家!如果我想搜索单词search会怎么样?这是一个很好的观点。。。这可能是一个愚蠢的想法,不允许该关键字。我正在努力使这个表单愚蠢地证明,并且可能决定绝对地使用输入Labar代替使用默认值。如果必要的话,您可以考虑并回落到标签定位。或者干脆不要为不支持占位符的浏览器做占位符。jQuery中事件处理程序的有用比较我只浏览了这篇文章,但它看起来是很好的信息。但不要使用
.live()
。从jQuery 1.7开始,它就贬值了,其功能与使用
.delegate()
相同。是的,这是.live()的缺点之一:)
if($("#global-search").val() == "Search")
    $("#global-search").val("");
function clearValue() {
    if ($("#global-search").val() == "Search") {
        $("#global-search").val('');
    }
}