javascript - 在 html 文件中使用 JavaScript chop 变量

标签 javascript variables trim

我想使用 JavaScript trim 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>

此解决方案 ( How to trim a string after a specific character in java ") 似乎很接近,但我不确定如何在我的文件中实现此代码。

谢谢。

最佳答案

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

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

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;

    } 

请注意,这假设了一些事情:

  • 描述中只有 1 个“$”
  • 价格总是排在您想要保留的所有其他东西之后,并且您需要的东西之后就没有了
  • 描述相对较短。如果“$”之前有 1000 个单词,则此方法效率不高。

关于javascript - 在 html 文件中使用 JavaScript chop 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24619566/

相关文章:

javascript - Bootstrap 模式不会在提交时关闭

javascript - 仅将颜色应用于 Chart.js 折线图的下部

javascript - 如何获取json变量的关键字?

c - C 中的参数变量

javascript - 从 nodejs crypto 返回的字符串中 trim 非 ascii 字符

javascript - 如何将单选按钮逻辑放入 *ngFor 中?

javascript - 知道 “audio”标签html何时被播放

jquery - 当 fancybox 窗口关闭时将变量传递回父级

php - 如何在将Excel导入mysql时修剪前导空格

php - 在回调中使用 `Undefined Property` 时,避免 PHP 中的 `isset()` 吗?