簡體   English   中英

從dom元素ID中刪除字符串

[英]Remove of string from dom element id

我需要從dom中的元素ID中刪除一個字符串(“ DTE_Field_”)。

<select id="DTE_Field_CD_PAIS" dependent-group="PAIS" dependent-group-level="1" class="form-control"></select>

var str=$(el).attr("id");
str.replace("DTE_Field_","");

attr()方法與callback一起使用 這將遍歷元素,您可以獲取舊的屬性值作為回調參數,可以通過使用String#replace方法返回DTE_FIELD字符串來更新屬性。

$('select').attr('id', function(i, oldId) {
  return oldId.replace('DTE_field_', '');
});

 $('select').attr('id', function(i, oldId) { return oldId.replace('DTE_Field_', ''); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select id="DTE_Field_CD_PAIS" dependent-group="PAIS" dependent-group-level="1" class="form-control"></select> 


如果不總是選擇元素,則可以使用attribute contains selector (或者如果DTE_field_始終位於開頭,則使用attribute starts with selector )。

$('[id*="DTE_field_"]').attr('id', function(i, oldId) {
  return oldId.replace('DTE_field_', '');
});

您可以拆分string( id )並使用pop()方法獲取數組的最后一個元素

var str=$('#DTE_Field_CD_PAIS').attr("id");
alert(str.split("DTE_Field_").pop());

JSFIDDLE

像這樣使用:

var string=$('#DTE_Field_CD_PAIS').attr("id");
console.log(str.split("DTE_Field_").pop());
$('[id^="DTE_FIELD_"]').each(function () {
   $(this).attr('id', $(this).attr('id').replace('DTE_FIELD_',''));
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM