0
我正在嘗試編寫一個腳本,它將在下拉框下方添加按鈕,並根據單擊按鈕更改值。這裏有給3個獨立的下拉菜單:按鈕單擊更改選項
<fieldset>
<div style="float: left;">
<div><label>Number of big seeds</label> <select class="form-control" name="big"> <optgroup label="big"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></optgroup> </select></div>
<div><label>Number of small seeds</label> <select class="form-control" name="small"><optgroup label="small"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></optgroup> </select></div>
<div><label>Number of tiny seeds</label> <select class="form-control" name="tiny"><optgroup label="tiny"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option> </optgroup> </select></div>
這裏是我在腳本中失敗的嘗試:
$(document).ready(function() {
//Variables for buttons
var $0 = $('<button type="button" class="0" id="0">0</button>');
var $1 = $('<button type="button" class="0" id="1">1</button>');
var $2 = $('<button type="button" class="0" id="2">2</button>');
var $3 = $('<button type="button" class="0" id="3">3</button>');
var $4 = $('<button type="button" class="0" id="4">4</button>');
var $5 = $('<button type="button" class="0" id="5">5</button>');
var $6 = $('<button type="button" class="1" id="0">0</button>');
var $7 = $('<button type="button" class="1" id="1">1</button>');
var $8 = $('<button type="button" class="1" id="2">2</button>');
var $9 = $('<button type="button" class="1" id="3">3</button>');
var $10 = $('<button type="button" class="1" id="4">4</button>');
var $11 = $('<button type="button" class="1" id="5">5</button>');
var $12 = $('<button type="button" class="2" id="0">0</button>');
var $13 = $('<button type="button" class="2" id="1">1</button>');
var $14 = $('<button type="button" class="2" id="2">2</button>');
var $15 = $('<button type="button" class="2" id="3">3</button>');
var $16 = $('<button type="button" class="2" id="4">4</button>');
var $17 = $('<button type="button" class="2" id="5">5</button>');
//Add buttons
$('.form-control').eq(0).after($0,$1,$2,$3,$4,$5);
$('.form-control').eq(1).after($6,$7,$8,$9,$10,$11);
$('.form-control').eq(2).after($12,$13,$14,$15,$16,$17);
});
//Click event
$(":button").click(function(){
var thisClass = parseInt($(this).attr('class'));
var thisID = parseInt($(this).attr('id'));
$('.form-control').eq(thisClass).val(thisID);
});
有人能告訴我我哪裏出錯了嗎?
那麼有什麼問題,它似乎工作正常 - > https://jsfiddle.net/zqxrp016/ – adeneo
奇怪的是,當我嘗試在網站外使用它時,按鈕不會改變任何東西。 – Somethingorother
另一方面,您應該努力避免使用無意義的名稱,如一系列數字,因爲這會使代碼非常難以閱讀和調試。相反,每個東西(變量,函數,類等)都應該有一個有意義的名稱來描述它是什麼或做什麼。 –