修改Span之外的文本

时间:2016-05-29 11:33:23

标签: javascript

最近我在配置span表外的文本时遇到了麻烦,我只想修改一个特定的字符串,但我尝试的一切都没有正常工作,我想在这里做的是修改

中的文本
  

您有资格发送最多0件商品的礼品,您有0件商品。

  

你有资格......,你有500件物品

<span id="giftFee"></span>
You are eligible to send gifts of up to 0 items, you have 0 items.<br><br>
Gifting items will automatically transfer coins from your account to the recipient<br>

链接:jsFiddle

1 个答案:

答案 0 :(得分:2)

要访问<span>元素之后的textNode纯JavaScript而不是jQuery - 可能更容易:

// get the <span> element from the document using
// the getElementById() method:
let span = document.getElementById('giftFee');

// if we found an element with that id and that element
// has a nextSibling and that nextSibling hasa nodeType 
// of 3 (meaning the nextSibling is a textNode):
if (span && span.nextSibling && span.nextSibling.nodeType === 3) {

  // we access that nextSibling, and update its nodeValue
  // (the text of the textNode) to the supplied string:
  span.nextSibling.nodeValue = 'Some other arbitrary string.';
}

let span = document.getElementById('giftFee');

if (span && span.nextSibling.nodeType === 3) {
  span.nextSibling.nodeValue = 'Some other arbitrary string.';
}
<span id="giftFee"></span> You are eligible to send gifts of up to 0 items, you have 0 items.

JS Fiddle demo

为了使它更具功能性和实用性,这里有一个允许进一步修改的功能:

// naming the function and setting the opts as an
// Object by default (to prevent errors using
// Object.keys() within the script):
function updateAdjacent(opts = {}) {

  // using 'let' (instead of 'var') to declare
  // variables:

  // settings.wrap :  Boolean, String
  //                  false: the adjacent element
  //                  will not be wrapped,
  //                  true: the adjacent element
  //                  will be wrapped in the same
  //                  element-type as the target element
  // settings.text :  String,
  //                  The new text for the adjacent element
  // settings.target: HTMLElementNode,
  //                  the element whose next-sibling text-node
  //                  you wish to adjust.
  let settings = {
    'wrap': false,
    'text': 'new arbitrary string',
    'target': null
  };

  // Iterating over the array of keys of the opts Object returned
  // by Object.keys, using Array.prototype.forEach() along with
  // an Arrow function to update the settings to reflect the
  // user-supplied options (if no option is passed in the default
  // will be used), the only mandatory option that must be supplied
  // is settings.target:
  Object.keys(opts).forEach(key => settings[key] = opts[key]);


  // if no target is passed via the opts Object we quit here:
  if (settings.target === null) {
    return false;
  }

  // for brevity here we shorten the variable-names, and
  // declare both an 'adjacent' and 'wrapper' variable:
  let target = settings.target,
    wrap = settings.wrap,
    text = settings.text,

    // the next-sibling of the target element:
    adjacent = target.nextSibling,

    // empty variable in case we need to create a wrapper
    // element:
    wrapper;

  // if we have an adjacent element and that adjacent element
  // is of nodeType 3 (a textNode):
  if (adjacent && adjacent.nodeType === 3) {

    // if wrap is not-equal to (Boolean) false:
    if (wrap !== false) {

      // if wrap is Boolean true (no element-type was specified):
      if (wrap === true) {

        // we create a new element of the same type as the
        // target:
        wrapper = document.createElement(target.localName);

      // otherwise if the wrap variable is a String:
      } else if ('string' === typeof wrap) {

        // we create an element of that specified type:
        wrapper = document.createElement(wrap);
      }

      // retrieving the parentNode of the target, and using
      // Node.insertBefore() to append the new-child (wrapper)
      // before the existing adjacent node:
      target.parentNode.insertBefore(wrapper, adjacent);

      // moving the adjacent node into the wrapper:
      wrapper.appendChild(adjacent);
    }
  }

  // here we update the nodevalue of the adjacent node
  // which is still referenced by the 'adjacent' variable
  // whether it remains 'physically' adjacent or newly-wrapped:
  adjacent.nodeValue = text;

  // here we return the adjacent node (if it was never wrapped),
  // or the newly-created parentNode (if the adjacent node was
  // wrapped):
  return wrap === false ? adjacent : adjacent.parentNode;
}

updateAdjacent({
  'target': document.getElementById('giftFee'),
  'text': 'Whatever text you might care to add.'
});

function updateAdjacent(opts = {}) {
  let settings = {
    'wrap': false,
    'text': 'new arbitrary string',
    'target': null
  };

  Object.keys(opts).forEach(key => settings[key] = opts[key]);

  if (settings.target === null) {
    return false;
  }

  let target = settings.target,
    adjacent = target.nextSibling,
    wrap = settings.wrap,
    text = settings.text,
    wrapper;

  if (adjacent && adjacent.nodeType === 3) {
    if (wrap !== false) {
      if (wrap === true) {
        wrapper = document.createElement(target.localName);
      } else if ('string' === typeof wrap) {
        wrapper = document.createElement(wrap);
      }
      target.parentNode.insertBefore(wrapper, adjacent);
      wrapper.appendChild(adjacent);
    }
  }

  adjacent.nodeValue = text;

  return wrap === false ? adjacent : adjacent.parentNode;
}

updateAdjacent({
  'target': document.getElementById('giftFee'),
  'text': 'Whatever text you might care to add.'
});
span {
  border: 1px solid #000;
  display: inline-block;
  margin: 1em 0.5em 0 0;
  padding: 0.2em 0.5em;
}
span[id]::before {
  content: '(id: ' attr(id) ') ';
}
#newSibling {
  color: #f90;
}
<span id="giftFee"></span> You are eligible to send gifts of up to 0 items, you have 0 items.

JS Fiddle demo

当然,可以通过多种方式调用上述内容,并在需要时进行链接。例如,如果我们包装相邻元素(通过传递true),我们可以设置该新父项的id以应用样式表中找到的样式:

function updateAdjacent(opts = {}) {
  let settings = {
    'wrap': false,
    'text': 'new arbitrary string',
    'target': null
  };

  Object.keys(opts).forEach(key => settings[key] = opts[key]);

  if (settings.target === null) {
    return false;
  }

  let target = settings.target,
    adjacent = target.nextSibling,
    wrap = settings.wrap,
    text = settings.text,
    wrapper;

  if (adjacent && adjacent.nodeType === 3) {
    if (wrap !== false) {
      if (wrap === true) {
        wrapper = document.createElement(target.localName);
      } else if ('string' === typeof wrap) {
        wrapper = document.createElement(wrap);
      }
      target.parentNode.insertBefore(wrapper, adjacent);
      wrapper.appendChild(adjacent);
    }
  }

  adjacent.nodeValue = text;

  return wrap === false ? adjacent : adjacent.parentNode;
}

updateAdjacent({
  'target': document.getElementById('giftFee'),
  'wrap': true
}).id = 'newSibling';
span {
  border: 1px solid #000;
  display: inline-block;
  margin: 1em 0.5em 0 0;
  padding: 0.2em 0.5em;
}
span[id]::before {
  content: '(id: ' attr(id)') ';
}
#newSibling {
  color: #f90;
}
<span id="giftFee"></span> You are eligible to send gifts of up to 0 items, you have 0 items.

JS Fiddle demo

或者我们可以通过将<b>作为'b'选项值传递来包装opts.wrap元素,并直接更新其style属性以添加{{1 }}:

updateAdjacent({   'target':document.getElementById('giftFee'),   'wrap':'b',   'text':'无论你想添加什么文字。' }。style.textDecoration ='overline';

text-decoration
function updateAdjacent(opts = {}) {
  let settings = {
    'wrap': false,
    'text': 'new arbitrary string',
    'target': null
  };

  Object.keys(opts).forEach(key => settings[key] = opts[key]);

  if (settings.target === null) {
    return false;
  }

  let target = settings.target,
    adjacent = target.nextSibling,
    wrap = settings.wrap,
    text = settings.text,
    wrapper;

  if (adjacent && adjacent.nodeType === 3) {
    if (wrap !== false) {
      if (wrap === true) {
        wrapper = document.createElement(target.localName);
      } else if ('string' === typeof wrap) {
        wrapper = document.createElement(wrap);
      }
      target.parentNode.insertBefore(wrapper, adjacent);
      wrapper.appendChild(adjacent);
    }
  }

  adjacent.nodeValue = text;

  return wrap === false ? adjacent : adjacent.parentNode;
}

updateAdjacent({
  'target': document.getElementById('giftFee'),
  'wrap': 'b',
  'text': 'Whatever text you might care to add.'
}).style.textDecoration = 'overline';
span {
  border: 1px solid #000;
  display: inline-block;
  margin: 1em 0.5em 0 0;
  padding: 0.2em 0.5em;
}
span[id]::before {
  content: '(id: ' attr(id)') ';
}

或直接添加事件监听器:

<span id="giftFee"></span> You are eligible to send gifts of up to 0 items, you have 0 items.

updateAdjacent({
  'target': document.getElementById('giftFee'),
  'wrap': 'b',
  'text': 'Whatever text you might care to add.'
}).addEventListener('click', function(e){
  let target = e.target,
      opacity = window.getComputedStyle(target,null).opacity;

      target.style.opacity = opacity === '1' ? '0.5' : '1';
});
function updateAdjacent(opts = {}) {
  let settings = {
    'wrap': false,
    'text': 'new arbitrary string',
    'target': null
  };

  Object.keys(opts).forEach(key => settings[key] = opts[key]);

  if (settings.target === null) {
    return false;
  }

  let target = settings.target,
    adjacent = target.nextSibling,
    wrap = settings.wrap,
    text = settings.text,
    wrapper;

  if (adjacent && adjacent.nodeType === 3) {
    if (wrap !== false) {
      if (wrap === true) {
        wrapper = document.createElement(target.localName);
      } else if ('string' === typeof wrap) {
        wrapper = document.createElement(wrap);
      }
      target.parentNode.insertBefore(wrapper, adjacent);
      wrapper.appendChild(adjacent);
    }
  }

  adjacent.nodeValue = text;

  return wrap === false ? adjacent : adjacent.parentNode;
}

updateAdjacent({
  'target': document.getElementById('giftFee'),
  'wrap': 'b',
  'text': 'Whatever text you might care to add.'
}).addEventListener('click', function(e) {
  let target = e.target,
    opacity = window.getComputedStyle(target, null).opacity;

  target.style.opacity = opacity === '1' ? '0.5' : '1';
});
span {
  border: 1px solid #000;
  display: inline-block;
  margin: 1em 0.5em 0 0;
  padding: 0.2em 0.5em;
}
span[id]::before {
  content: '(id: ' attr(id)') ';
}

参考文献: