我怎样才能更有效地写这个?

时间:2013-09-11 18:46:03

标签: javascript scope performance

这是否是最好的方法,我不在乎 - 但在这种情况下,我有两个相同的搜索栏,我根据屏幕宽度切换。一个显示移动设备,一个显示桌面。下面的代码效果很好,但重复次数很多,必须有更好的方法来编写它。

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 +'”]'的变量,我也希望能够以一种仍然可以使用的方式定义视口一次在功能内。但是我的尝试都遇到了范围问题。

1 个答案:

答案 0 :(得分:0)

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

$('.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();
    }
});

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