2014-02-17 69 views
1

我正在寫一個函數,它遍歷一個DOM並向節點的開始處添加空格。這裏是什麼樣子:更新jQuery對象的屬性沒有效果

$ = require 'jquery' 

addSpaces = (node, noSpace=true) -> 
    for child in ($ node).prop('childNodes') 
    # nodeType of 3 means a text node 
    if child.nodeType is 3 
     if child.textContent 
     child.textContent = child.textContent.trim() 
     if child.textContent[0] not in [',', '.', ':', ';', ')'] 
      if noSpace then noSpace = false 
      else 
      console.log "About to add a space, text is '#{child.textContent}'" 
      child.textContent = ' ' + child.textContent 
      console.log "Added a space, now text is '#{child.textContent}'" 
    # nodeType of 1 means a DOM element, recurse down 
    else if child.nodeType is 1 
     addSpaces child, noSpace 

input = "<foo><bar>I<baz>need</baz><qux>some</qux>spaces</bar></foo>" 

node = $ input 

console.log node.prop 'outerHTML' 
addSpaces node 
console.log node.prop 'outerHTML' 

運行這給

> coffee spaces.coffee 
<foo><bar>I<baz>need</baz><qux>some</qux>spaces</bar></foo> 
About to add a space, text is 'need' 
Added a space, now text is 'need' 
About to add a space, text is 'some' 
Added a space, now text is 'some' 
About to add a space, text is 'spaces' 
Added a space, now text is 'spaces' 
<foo><bar>I<baz>need</baz><qux>some</qux>spaces</bar></foo> 

所以,我們可以看到該行child.textContent = ' ' + child.textContent沒有影響:空間沒有得到增加(即使該範圍內一個功能)。這裏發生了什麼?我是jQuery的新手,我猜測它與此有關,但我不確定是什麼。

回答

1

對此的解決方案是使用nodeValue代替textContent

$ = require 'jquery' 

addSpaces = (node, noSpace=true) -> 
    for child in ($ node).prop('childNodes') 
    # nodeType of 3 means a text node 
    if child.nodeType is 3 
     if child.nodeValue 
     child.nodeValue = child.textContent.trim() 
     if child.nodeValue[0] not in [',', '.', ':', ';', ')'] 
      if noSpace then noSpace = false 
      else 
      console.log "About to add a space, text is '#{child.nodeValue}'" 
      child.nodeValue = ' ' + child.nodeValue 
      console.log "Added a space, now text is '#{child.nodeValue}'" 
    # nodeType of 1 means a DOM element, recurse down 
    else if child.nodeType is 1 
     addSpaces child, noSpace 

input = "<foo><bar>I<baz>need</baz><qux>some</qux>spaces</bar></foo>" 

node = $ input 

console.log node.prop 'outerHTML' 
addSpaces node 
console.log node.prop 'outerHTML'