Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
获取元素的文本节点并使用Javascript对其进行操作_Javascript - Fatal编程技术网

获取元素的文本节点并使用Javascript对其进行操作

获取元素的文本节点并使用Javascript对其进行操作,javascript,Javascript,我有一套包含价格的要素: <em class="price">$859</em> <em class="price">$159</em> <em class="price">$850</em> <em class="price">$350</em> <em class="price">$560</em> <em class="price">$200</em&g

我有一套包含价格的要素:

<em class="price">$859</em>
<em class="price">$159</em>
<em class="price">$850</em>
<em class="price">$350</em>
<em class="price">$560</em>
<em class="price">$200</em>
<em class="price">$250</em>
<em class="price">$900</em>
这不会在控制台中记录任何内容


在文档加载时使用jQuery应用所需的Javascript

使用循环可能最适合您想要做的事情,并且在已经加载jQuery时使用它。试试这个:

function setCheckPrice() {
  $('.price').each(function(key, val) {
    var price = $(val).html().replace('$', '');
    var newPrice = parseInt(price) * 10;
    $(val).after('<em class="new-price">$' + newPrice + '</em>');
  });
}

setCheckPrice();

您可以通过更改5来瞄准其他元素。

您可以使用
document.getElementsByClassName('price')
。试试这个,然后把你到目前为止已经试过的东西贴出来。这是一个很好的答案,但是出于某种原因,它抛出了一个
NaN
作为新输出的价格。如果我想把这个应用到一个元素上呢?我会在抓取元素后删除
。每个
吗?这种更改对单个项目起到了作用!我注意到的一件奇怪的事情是,对于具有四位数字的原始数字,计算结果以一个
NaN
结尾。我更新了原始函数以使用
parseInt(price)
,因为这样可以防止
NaN
,您用它更新代码了吗?
function setCheckPrice() {
  $('.price').each(function(key, val) {
    var price = $(val).html().replace('$', '');
    var newPrice = parseInt(price) * 10;
    $(val).after('<em class="new-price">$' + newPrice + '</em>');
  });
}

setCheckPrice();
function setCheckPrice() {
  var element = $('.price:nth-of-type(5)');
  var price = $(element).html().replace('$', '');
  var newPrice = parseInt(price) * 10;
  $(element).after('<em class="new-price">$' + newPrice + '</em>');
}

setCheckPrice();