更新jQuery对象的属性无效

时间:2014-02-17 22:40:53

标签: jquery dom coffeescript

我正在编写一个迭代DOM的函数,并在节点的开头添加空格。这是它的样子:

$ = 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 个答案:

答案 0 :(得分: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'