一种简单的方法(避免混乱的字符串操作):
var editText = "<span class='hover-content' data-hover-id='2' >Some text</span>",
tmp = document.createElement('div');
tmp.innerHTML = editText;
tmp.style.display = 'none';
document.getElementsByTagName('body')[0].appendChild(tmp);
var hoverId = tmp.getElementsByTagName('span')[0].getAttribute('data-hover-id');
tmp.parentNode.removeChild(tmp);
alert(hoverId);
JS 小提琴演示。
但是,鉴于:
该字符串被操纵。
我还将提供:
var editText = "<span class='hover-content' data-hover-id='2' >Some text</span>",
parts = editText.split(/\s+/),
hoverId = -1;
for (var i = 0, len = parts.length; i < len; i++) {
if (parts[i].indexOf('data-hover-id') == 0) {
hoverId = parseInt(parts[i].split('=')[1].match(/\d+/), 10)
}
}
console.log(hoverId);
JS 小提琴演示。
还有一个更简洁(虽然可能很脆弱)的解决方案:
var editText = '<span class="hover-content" data-hover-id=2 >Some text</span>',
hoverId = editText.match(/\s?data\-hover\-id=(?:['"])?(\d+)(?:['"])?/)[1] || -1;
console.log(hoverId);
Works with single-quoted ('
) attribute-values: JS Fiddle demo.
Works with double-quoted ("
) attribute-values: JS Fiddle demo.
Work with unquoted values: JS Fiddle demo.