![](/img/trans.png)
[英]How to execute JavaScript code when a user clicks the button multiple times?
[英]Execute JavaScript code multiple times in different threads when the class is used by multiple elements
我有一個將執行的JavaScript代碼,可以說使用ID #script-name
。 我處於一種情形,當標識符被多個(例如兩個HTML元素)使用時,我想在不同的線程中多次執行它。 因此,我將#script-name
重構為類.script-name
。 可以說我有以下代碼:
if (document.getElementsByClassName('script-name')[0]) { var obj = $(".script-name"); obj.animate({ marginLeft: obj.css("height") }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="script-name" style="height: 25px; background-color: red;">height 25px</div> <div class="script-name" style="height: 50px; background-color: blue;">height 50px</div>
該代碼會將兩個元素都設置為marginLeft: "25px"
動畫,在此,我希望第二個元素根據其自身的marginLeft: obj.css("height")
進行動畫。 有沒有辦法在不使用另一個代碼塊創建另一個標識符的情況下實現這一目標?
if (document.getElementById('script-name')) { var obj = $("#script-name"); obj.animate({ marginLeft: obj.css("height") }); } if (document.getElementById('script-name-2')) { var obj = $("#script-name-2"); obj.animate({ marginLeft: obj.css("height") }); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="script-name" style="height: 25px; background-color: red;">height 25px</div> <div id="script-name-2" style="height: 50px; background-color: blue;">height 50px</div>
您可以使用jQuery .each()
依次處理每個元素:
$(".script-name").each(function() {
var $this = $(this);
$this.animate({
marginLeft: $this.css("height");
});
});
請注意,實際上不需要檢查是否存在任何具有“腳本名稱”類的元素。 如果不執行任何操作,則以上代碼將不執行任何操作,而不會導致任何類型的運行時錯誤。
您可以使用$ .each()來做到這一點。 而且$(selector).somefn()
通常不會拋出空指針,因此您可以擺脫空檢查
$("#script-name-2,#script-name").each(function(){ $(this).animate({ marginLeft: $(this).css("height") }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="script-name" style="height: 25px; background-color: red;">height 25px</div> <div id="script-name-2" style="height: 50px; background-color: blue;">height 50px</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.