我的页面上有一个下拉列表:
<div class="dropdown" data-method="redirect">
<select id="weekselect">
<option>Select a week</option>
<option value="http://sample.com/page1/action">This Week</option>
</select>
</div>
选择a后,它将被重定向到页面http://sample.com/page1/action。它在PC上工作正常,但是当在移动设备上查看网站时,重定向不起作用,它只是重定向到页面undefined
。
用于重定向的JS代码是:
$(window).load(function (event) {
$(document).on('click','#menu-bars', function (event) {
$('body').toggleClass('nav-collapsed');
$.scrollTo(0, 'fast');
});
var selectList = $('select');
if( !$('html').is('.touch') ){
selectList.select2({
minimumResultsForSearch: -1
});
}
selectList.on("change", function (e) {
var parent = $(this).parents('.dropdown');
var method = parent.data('method');
if (method == 'redirect') {
window.location = e.val;
}
可能是在移动设备上查看网站时,window.location = e.val;
不包含任何值。
重定向页面时,js无法正常工作的原因是什么?
答案 0 :(得分:1)
请尝试使用e.val
$(this).val();
还使用window.location.href
答案 1 :(得分:0)
您需要更改
if (method == 'redirect') {
window.location = e.val;
}
到
if (method == 'redirect') {
window.location = $(this).val();
}
e
不是调用对象,它是事件对象。见the docs
你真的应该把方法改为:
selectList.on("change", function (e) {
var caller = $(this);
var parent = caller.parents('.dropdown');
var method = parent.data('method');
if (method == 'redirect') {
window.location = caller.val();
}
保存对$(this)
的多次通话效率更高。
同样parents()
可以返回多个对象,尤其是如果您使用类选择器,那么围绕此区域的代码不是很强大。如果你不期望使用倍数,你可以处理它(可能使用each()),如果你不使用parent()