【问题标题】:Updating attribute of jQuery object has no effect更新jQuery对象的属性没有效果
【发布时间】:2014-03-17 10:29:21
【问题描述】:

我正在编写一个遍历 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 新手,我猜它与此有关,但我不确定是什么。

【问题讨论】:

    标签: jquery dom coffeescript


    【解决方案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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 2015-11-04
      • 1970-01-01
      相关资源
      最近更新 更多