[英]How to strip non-digit characters from an id attribute with JavaScript
我正在從列表標簽中讀取ID,然后將其添加到pre
標簽中,如下所示:
$('pre').each(function() {
$(this).attr('id', $(this).closest('li').attr('id'));
});
例如,列表標記具有以下ID:
<li id="Comment_123">
對於pre標簽,我想從ID中刪除前8個字符; 所以pre標簽應該變成這個id:
<pre id="123">
如何用已有的代碼實現這一目標?
如果您知道所有ID具有相同的結構,則可以刪除_(含)之前的內容。
var id = $(this).closest('li').attr('id').split('_').pop();
如果設置為前8個字符,則使用substring
var id = $(this).closest('li').attr('id');
var shortened = id.substring(8, id.length);
$(this).attr('id', shortened);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.