目前還不清楚你想用新滑塊做什麼,但是你的代碼有幾個問題。首先你要在第一個滑塊(而不是第二個滑塊)內添加第二個滑塊div,然後在第一個滑塊上添加與第一個滑塊相同的ID - 你幾乎肯定會想要不同的ID。最後,您需要初始化新元素上的滑塊。
所以,這樣的事情(取代你的$(document).on(...) { ... }
)。
// Global variable to count make the ids different (could embed this on some object)
slider_count = 1;
$(document).on('click', '.addNew', function() {
// Work out the id for the new slider
var new_slider_id = 'slider'+slider_count;
// Attach it to the end of the body -- you might want a 'container' DIV here
$('body').append("<div id='"+new_slider_id+"'></div>");
// Initialize the new slider
$("#"+new_slider_id).slider();
// Update our unique id count
slider_count = slider_count + 1;
});
您還需要做一些事情來處理這些值 - 可以將它們加在一起,也可以有單獨的總和。你可以給所有滑塊DIV一個類,然後使用each
來檢查這些值。或者,由於您有權訪問slider_count變量,因此您可以計算出滑塊及其ID的數量。
希望有所幫助。
編輯:根據我認爲你想要做的事情添加以下內容,我會嘗試解釋發生了什麼。
首先,讓生活容易通過在HTML沒有嵌入第一滑塊,只放了塊那裏以後將持有滑塊:
<p>
<button class="addNew">Add</button>
<label for="amount">Donation amount ($50 increments):</label>
<input type="text" id="amount" style="border: 0; color: #f6931f; font-weight: bold;" />
</p>
<div id="container">
現在,你需要一種方法來創建滑塊,它是有道理的使它成爲一個函數,因爲它響應於多個事件(頁面加載和按鈕單擊)而被調用。
function createSlider() {
// Work out the id for the new slider
var new_slider_id = 'slider'+createSlider.counter;
// Create a slider with that id and a common slider class in the container
$('#container').append("<div class='amount_slider' id='"+new_slider_id+"'></div>");
// Initialize the new slider
$("#"+new_slider_id).slider({
value:100,
min: 0,
max: 500,
step: 50,
change: function() {
updateAmount();
}
});
// Update the amount now to take account of the new default value
updateAmount();
// Update our unique id count
createSlider.counter = createSlider.counter + 1;
}
當它被調用時,它會在DIV容器中創建一個新的滑塊,並使用您使用的相同選項對其進行初始化。它使用計數器爲每個滑塊提供不同的ID(從零開始)。計數器作爲一個變量存儲在函數中(當JavaScript使用時,它可以實現靜態)。全局變量也可以工作,但這至少表明該計數器僅被該函數使用。
該函數調用updateAmount()
,無論是在更改滑塊後還是創建滑塊之後。第二次調用是必要的,因爲我們在$ 100上啓動滑塊,以便在創建滑塊時將需求添加到該量。更新事件發生在change
之後,您使用的是slide
,它會觸發任何移動,因此反映的數量往往是錯誤的。如果其他內容改變了基礎值 - 也就是另一個腳本,那麼更改也會起作用。
的updateAmount()
功能使用,我們給我們的所有滑塊同一類,所以我們可以使用jQuery的類匹配和each
功能要經過他們的所有,這樣的事實:
function updateAmount() {
var new_amount = 0;
$('.amount_slider').each(function() {
new_amount = new_amount += $(this).slider('value');
});
$("#amount").val("$" + new_amount);
}
正如我以前說過,由於您知道計數器的當前值,因此您也可以手動計算滑塊ID列表並使用它。
最後通過在頁面加載時創建第一個滑塊(記住要清零計數器,這在JavaScript中不是必須的,但通常是很好的做法)並將創建操作附加到添加按鈕:
// Create the first slider
$(document).ready(function() {
createSlider.counter = 0;
createSlider();
});
// Attach the createSlider() action to the 'add' button
$(document).on('click', '.addNew', function() {
createSlider();
});
而就是這樣 - 如果這不是你想要做的,希望你可以看到邏輯是如何工作的,並改變它使它按照你的想法工作。
感謝您回覆。那麼我不清楚我要做什麼,因爲那不是我問的問題。當你點擊按鈕時,你的編輯會添加一個新的滑塊嗎? – AyeTry
您的解決方案沒有工作,只是得到相同的結果 – AyeTry
對不起,它確實有點,但它沒有長步增量滑塊,並且不顯示捐款數量增量的變化 – AyeTry