2 回答
TA贡献1872条经验 获得超4个赞
用代码补充 JS 以清除不需要的内容。只要所述内容包含在可以由 css 选择器提取的已知标签中(在给定的情况下:),此方法就可以工作em。
display消隐是通过将不需要的元素的 Css 属性临时设置为 来实现的none。测试时没有明显的效果(又名闪烁)。
在示例中,为了演示目的,已将一个附加子项(以粗体显示)添加到标记为已检查的内容中。
function copyText(){
var outputText = "";
var items= document.getElementsByClassName('checked');
// BEGIN - supplement to the original code
Array.from(items).forEach ( pnode => {
// Complement this selector to remove whatever is unwanted.
// '*' removes all child elements.
let nodelist_toBlank = pnode.querySelectorAll('em')
;
// Blank the unwanted content, saving the original Css property value
Array.from(nodelist_toBlank).forEach ( pnode_toBlank => {
pnode_toBlank.setAttribute ( 'data-style-display', pnode_toBlank.style.display );
pnode_toBlank.style.display = 'none';
});
// Add data from node to the string buffer. Elements with Css 'display' property set to 'none' are skipped
outputText += pnode.innerText+"\n";
// Unblank. Restore the original Css property value
Array.from(nodelist_toBlank).forEach ( pnode_toRestore => {
pnode_toRestore.style.display = pnode_toRestore.getAttribute ( 'data-style-display' );
pnode_toRestore.removeAttribute ( 'data-style-display' );
});
});
// END - supplement to the original code
//
// Original loop deleted!
var output = document.getElementById('output');
output.innerText = outputText;
var range = document.createRange();
range.selectNodeContents(output);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
output.style.display = 'none';
}
<li class="checked"><p>This<em>I don't need this</em><b>I want this</b></p>
<input type="checkbox"></li>
<li class="unchecked"><p>That</p>
<input type="checkbox"></li>
<button onclick="copyText()">Copy</button>
<div id="output"></div>
评论
根据MDN,execCommand是一个过时的功能,不应再使用。
TA贡献1863条经验 获得超2个赞
更新循环以包含 if 语句:
var em = document.querySelector('em');
for(var i = 0; i < items.length; i++) {
if (em,items[i].contains(em)){
outputText += items[i].innerText.replace(em.innerText, "")+"\n";
console.log(em.innerText);
}else{
outputText += items[i].innerText+"\n";
}
}
添加回答
举报
