[英]Getting Select Tag to work as a on click function in JQuery
因此,我設置了該選項卡,使其與台式機中的單擊鏈接一樣工作,但是在平板電腦和移動設備中,我需要它成為具有相同功能的選擇下拉列表。
這是在桌面上作為鏈接的代碼:
jQuery(document).ready(function($) {
$('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = $(this).attr('href');
// Show/Hide Tabs
$('.tabs ' + currentAttrValue).show().siblings().hide();
// Change/remove current tab to active
$(this).parent('li').addClass('active-tab').siblings().removeClass('active-tab');
e.preventDefault();
});
這很完美,現在這就是select標簽的功能:
$('.tabs .tab-select select').on('change', function(e) {
var currentAttrValue = $(this).attr('option');
$('.tabs ' + currentAttrValue).show().siblings().hide();
});
如何獲取選擇標簽代碼?
首先,您不需要執行$('.tabs .tab-select select')
(這意味着將選擇標記作為.tab-select的子代 ),因為您使用的select
元素具有.tab-select
類本身。
其次, $(this).attr('option')
在更改處理程序中未定義,因為它在select元素本身中引用了select
屬性 (沒有HTML標記具有select屬性)。
解決方法 :要獲取當前選定的 選項 ,應使用jQuery的:selected
Selector ,並將選項的值(或文本)與選項卡的 ID串聯在一起,如下所示:
$('.tabs .tab-select').on('change', function(e){
var currentOption = $('#' + $(this).attr('id') + ' option:selected').text();
$('#tab' + currentOption).show().siblings().hide();
});
JSfiddle 。
它在JS小提琴中效果很好,但是當我將其添加到整個JQuery中時,它不起作用
jQuery(document).ready(function($) {
$('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = $(this).attr('href');
////Show/Hide Tabs
$('.tabs ' + currentAttrValue).show().siblings().hide();
////Change/remove current tab to active
$(this).parent('li').addClass('active-tab').siblings().removeClass('active-tab');
e.preventDefault();
});////desktop
$('.tabs .tab-select').on('change', function(e){
var currentOption = $('#' + $(this).attr('id') + ' option:selected').text();
$('#tab' + currentOption).show().siblings().hide();
});////mobile
}); //// JQuery塊的結尾
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.