Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.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/9/apache-flex/4.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
在html文件中使用JavaScript截断变量_Javascript_Variables_Trim - Fatal编程技术网

在html文件中使用JavaScript截断变量

在html文件中使用JavaScript截断变量,javascript,variables,trim,Javascript,Variables,Trim,我想使用javascript修剪html文件中的“description”变量以删除价格 一个典型的描述是“帽子,红色-$5.99”,在所有情况下,价格-即“$”之后的所有内容都不应显示 以下是html代码的外观: <tr class="font1"> <td valign="top" align="left" width="15%">[id]</td> <td valign="top" align="left" widt

我想使用javascript修剪html文件中的“description”变量以删除价格

一个典型的描述是“帽子,红色-$5.99”,在所有情况下,价格-即“$”之后的所有内容都不应显示

以下是html代码的外观:

<tr class="font1">
        <td valign="top" align="left" width="15%">[id]</td>
        <td valign="top" align="left" width="53%">[description]  
</tr>

[id]
[说明]
这个解决方案(“)看起来很接近,但我不确定如何在我的文件中实现这段代码


谢谢。

既然您想在
$
处拆分字符串,您可以将
$
的函数用作除味器

例如:

var fullDescription = 'hat, red $5.99';
var description = fullDescription.split('$')[0] //Split returns an array of the string divided on either side of the $, so take the first element.
变量
description
现在将包含
'hat,red'

1)“Java”和“JavaScript”是不同的东西。“split”概念仍然是您想要的方式,但语法不同

2) 如果您想访问和操作HTML内容,通常最好使用一个类(可对多个元素重复)或一个唯一的id(页面上只有1个)对于你想改变的元素。你的HTML目前似乎没有这个,所以唯一的选择是抓住所有的<代码> <代码>元素,并删除所有的价格。如果这就是你想要的,得分!如果不是,那么你需要考虑为选定的单元格或类似的东西添加一个类。

3) 一旦找到了获取内容的方法,就可以在描述中搜索“$”并将其前面的所有内容放入新字符串中,然后放入单元格中

    //returns every td element, since you have no classes or ids
    var allCells = document.getElementsByTagName('td');

    //loop through the list of td elements
    for (var i=0; i < allCells.length; i++) {

        //get the actual HTML content of the cell 
        var currentCellText = allCells[i].innerHTML;

        //split the description text at the '$' and replace the table cell contents            
        var newText = currentCellText.split('$')[0];
        allCells[i].innerHTML = newText;

    } 
//返回每个td元素,因为您没有类或id
var allCells=document.getElementsByTagName('td');
//循环浏览td元素列表
对于(var i=0;i
请注意,这假设了以下几点:

  • 说明中只有1“$”
  • 价格总是排在你想要保留的所有东西之后&你需要的东西之后就没有了
  • 说明相对较短。如果在“$”之前有1000个单词,这种方法将不会有效

那么您想要
5.99美元
帽子,红色
中的
帽子,红色-5.99美元
?请再次确认。