簡體   English   中英

如何在以字符串表示的范圍內獲取ID?

[英]How can I get the id within a span represented as a string?

var span = '<span class="we w_o_r_d_s" id="we" contenteditable="false">we</span>' 

console.log(span.id);
console.log(span.attr('id'));
console.log(span.getAttribute('id'));

var div = document.createElement('div');
div.innerHTML = span;


console.log(div.id);
console.log(div.attr('id'));
console.log(div.getAttribute('id'));



//I want to log `we`

http://jsfiddle.net/3BTdk/1/

我看了這里,但沒明白。 謝謝。

創建一個jQuery對象,並使用.attr('id')獲取ID。

var span = '<span class="we w_o_r_d_s" id="we" contenteditable="false">we</span>'; 
var id = $(span).attr('id');

演示。

沒有jQuery版本:

var tmp = document.createElement('p'); 
tmp.innerHTML=span;
console.log(tmp.childNodes[0].id);

和演示。

您可以使用jQuery函數將字符串轉換為jQuery對象。 它將允許您在其上應用jQuery selectors / functions

現場演示

var span = jQuery ('<span class="we w_o_r_d_s" id="we" contenteditable="false">we</span>');
var id = span.attr('id');

如果頁面只有一個跨度

然后var id = $('span').attr('id');

http://jsfiddle.net/Vinay199129/3BTdk/3/

代替span.attr('id')使用$(span).attr('id')

您可能想將jQuery/$功能包裝在DOM元素周圍的原因應該很明顯。 這樣做使您能夠使用jQuery鏈接(如果需要)。

看看我更新的小提琴 ...

或使用此:

console.log($(span).attr('id'));

暫無
暫無

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

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