这是否是最好的方法,我不在乎 - 但在这种情况下,我有 2 个相同的搜索栏,我根据屏幕宽度进行切换。一个显示手机,一个显示桌面。下面的代码运行良好,但重复太多,必须有更好的编写方法。
的HTML:
<div class="search-wrp">
<input type="text" class="search" data-which="mobile" value="Search" />
<input type="button" value=" " 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=" " 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 + '"]' 使用一个变量,并且我还希望能够以一种仍然可以在函数中使用的方式定义一次视口. 但是,我的尝试都遇到了范围问题。