<div>select this<strong>dfdfdf</strong></div>
<div><span>something</span>select this<strong>dfdfdf</strong></div>
내가 div 태그의 값을 선택하지만, XPath를 사용하여 자식 요소JQuery와 텍스트를 선택
//output
select this
<div>select this<strong>dfdfdf</strong></div>
<div><span>something</span>select this<strong>dfdfdf</strong></div>
내가 div 태그의 값을 선택하지만, XPath를 사용하여 자식 요소JQuery와 텍스트를 선택
//output
select this
$("div").contents().each(function(i) {
//the function is applied on the node.
//therefore, the `this` keyword is the current node.
//check if the current element is a text node, if so do something with it
});
을 포함하지 않도록 JQuery와하거나 자바 스크립트를 어떻게 사용합니까, 당신은 단지 텍스트를 선택할 수 있습니다 div의 자식 노드. 원시 자바 스크립트.
var xpr = document.evaluate("//div/text()",document,null,
XPathResult.STRING_TYPE,
null);
console.log(xpr.stringValue);
> select this
당신은 텍스트 태그 산재 경우 :
<div>select this<strong>dfdfdf</strong>and this</div>
... 당신이
function $x(path, context, type) {
if (!context) context = document;
type = type || XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE;
var i,item,arr=[], xpr = document.evaluate(path, context, null, type, null);
for (i=0; item=xpr.snapshotItem(i); i++)
arr.push(item);
return arr;
}
var nodes = $x("//div/text()");
nodes.forEach(function(item) {
console.log(item.textContent);
});
> select this
> and this
(도우미가 배열되는 XPathResult 변환) 그들을 반복 할 수 (FF로 테스트, 방화산 로깅으로 테스트)
일반 JS 버전 :
function getDirectTextContent(element) {
var text= [];
for (var i= 0; i<element.childNodes.length; i++) {
var child= element.childNodes[i];
if (child.nodeType==3) // Node.TEXT_NODE
text.push(child.data);
}
return text.join('');
}
인수는 (I, 노드)에, 그리고 테스트 node.nodeName에 함수 :.. $ ("DIV") 내용() 각 (함수 (i, node) { if (node.nodeName == "#text") console.log (node.textContent); }}); – Chadwick
함수가 노드에 적용됩니다. 그러므로'this' 키워드는 현재 노드입니다. – geowa4