0

这是否是最好的方法,我不在乎 - 但在这种情况下,我有 2 个相同的搜索栏,我根据屏幕宽度进行切换。一个显示手机,一个显示桌面。下面的代码运行良好,但重复太多,必须有更好的编写方法。

的HTML:

<div class="search-wrp">
    <input type="text" class="search" data-which="mobile" value="Search" />
    <input type="button" value="&nbsp;" class="go sprite" data-which="mobile" />
</div>

<div class="search-wrp">
    <input type="text" class="search" data-which="desktop" value="Search" />
    <input type="button" value="&nbsp;" class="go sprite" data-which="desktop" />
</div>

JS:

 $('.search').focus(function () {
    var viewport = $(this).attr('data-which');
    if ($('.search[data-which="' + viewport + '"]').val().toLowerCase() == "search") {     $('.search[data-which="' + viewport + '"]').val(""); }
}).focusout(function () {
    var viewport = $(this).attr('data-which');
    if ($('.search[data-which="' + viewport + '"]').val() == "") { $('.search[data-which="' + viewport + '"]').val("Search"); }
}).keypress(function (event) {
    var viewport = $(this).attr('data-which');
    if (event.keyCode == '13') {
        event.preventDefault();
        $('.go[data-which="' + viewport + '"]').click();
    }
});

$('.go').click(function () {
    var viewport = $(this).attr('data-which');
    if ($('.search[data-which="' + viewport + '"]').val() == null || $('.search[data-which="' + viewport + '"]').val() == "Search") {
        alert("Please enter a search phrase.");
    } else {
        window.location = "http:" + "//" + window.location.host + "/Search.aspx?phrase=" + $('.search[data-which="' + viewport + '"]').val();
    }
});

我想为 '.search[data-which="' + viewport + '"]' 使用一个变量,并且我还希望能够以一种仍然可以在函数中使用的方式定义一次视口. 但是,我的尝试都遇到了范围问题。

4

1 回答 1

0

与其在每个函数内部重复调用,不如$('.search[data-which="' + viewport + '"]')将其存储在一个变量中。例如:

$('.search').focus(function () {
    var viewport = $(this).attr('data-which'),
        search = $('.search[data-which="' + viewport + '"]');
    if (search.val().toLowerCase() == "search") { search.val(""); }
}).focusout(function () {
    var viewport = $(this).attr('data-which'),
        search = $('.search[data-which="' + viewport + '"]');
    if (search.val() == "") { search.val("Search"); }
}).keypress(function (event) {
    var viewport = $(this).attr('data-which');
    if (event.keyCode == '13') {
        event.preventDefault();
        $('.go[data-which="' + viewport + '"]').click();
    }
});

$('.go').click(function () {
    var viewport = $(this).attr('data-which'),
        search = $('.search[data-which="' + viewport + '"]');
    if (search.val() == null || search.val() == "Search") {
        alert("Please enter a search phrase.");
    } else {
        window.location = "http:" + "//" + window.location.host + "/Search.aspx?phrase=" + search.val();
    }
});

如果您多次需要该值,请始终存储该函数的返回值。

于 2013-09-11T18:59:31.740 回答