[英]How can I get 2 attributes and I apply a function as a parameter?
我需要使用jQuery獲得2個屬性,並根據應用程序的狀態更改其中的值。
$(this).attr('id', function (i, val) {
return val.replace('More', 'Less');
});
上面的代碼非常完美,它可以滿足我的需求。 但是我需要這樣的東西:
$(this).attr('id, theOtherAttr', function (i, val) {
return val.replace('More', 'Less');
});
HTML看起來像這樣:
<a href="javascript:void(0)" id="BAMS_Q1_See_More_Clover_Station" theOtherAttr="BAMS_Q1_See_More_Clover_Station"></a>
有什么建議么?
請看一下這段代碼,因為這樣的代碼應該可以工作:
$(this).attr('id', myFunc).attr('theOtherAttr', myfunc)
通過使用額外的功能:
function myfunc(parameter1, parameter2) {
// do stuff
} ;
注意 :您始終可以使用.attr()
方法添加多個屬性:
.attr({
parameter1:"...",
parameter2:"..."
});
因此,在您的情況下,以下方法將是正確的方法:
$("*").attr('id', function(i, value) {
var attribute1 = value
var attribute2 = $(this).attr('secondattribute');
return ""
});
您可以使用$(this)
選擇器設置並獲取函數內的第二個屬性。
$("a").attr('id', function(i, val) { console.log(val); //First attribute let attr2 = $(this).attr('theOtherAttr'); //Getting the 2nd attr console.log(attr2); //Do your process with val and attr2 //Return to change the `id` attr return val.replace('More', 'Less'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="javascript:void(0)" id="BAMS_Q1_See_More_Clover_Station" theOtherAttr="BAMS_Q1_See_More_Clover_Station_theOtherAttr"></a>
如果2個屬性相同,則可以
$("a").attr("id", function(i, val) { //Set both $(this).attr({ id: val.replace('More', 'Less'), theOtherAttr: val.replace('More', 'Less') }); console.log( "id - ", $(this).attr("id") ); console.log( "theOtherAttr - ", $(this).attr("theOtherAttr") ); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="javascript:void(0)" id="BAMS_Q1_See_More_Clover_Station" theOtherAttr="BAMS_Q1_See_More_Clover_Station"></a>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.