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

Convert JS function to jQuery - (input field clear default value)

本文关键字:字段 输入 清除 默认值 jQuery- JS 函数 转换      更新时间:2023-09-26

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

我想做的只是从关键字字段onSubmit中删除默认值"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():http://api.jquery.com/on
  • .val():http://api.jquery.com/val
  • document.ready:http://api.jquery.com/ready/
  • jQuery选择器:http://api.jquery.com/category/selectors/
if($("#global-search").val() == "Search")
    $("#global-search").val("");
function clearValue() {
    if ($("#global-search").val() == "Search") {
        $("#global-search").val('');
    }
}