如何更改页面上的文字? (使用jQuery查找和替换?)

时间:2021-07-12 19:14:56

I have a block of hardcoded, uneditable HTML:

我有一块硬编码,不可编辑的HTML:

<td id="v65-onepage-ordercomments-value" width="61%" valign="top" colspan="2">
     Order Comments:&nbsp;(Optional)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
     <br>           
     <textarea name="Order_Comments" id="v65-onepage-ordercomments-input" rows="3" cols="55"></textarea>
</td>

I want to replace "Order Comments (Optional)", as well as all those non-breaking spaces. I would preferably like to replace it with other HTML, like a header and a paragraph tag. What is the best way to do this? My assumption is to do something like a find & replace using jQuery?

我想替换“Order Comments(Optional)”以及所有那些不间断的空格。我最好将其替换为其他HTML,如标题和段落标记。做这个的最好方式是什么?我的假设是使用jQuery做一些像find和replace这样的东西?

2 个解决方案

#1


2  

It it's always a textNode that is the first child of the parent div, you can do :

它总是一个textNode,它是父div的第一个子节点,你可以这样做:

var node = document.getElementById('v65-onepage-ordercomments-value').firstChild;
node.nodeValue = 'new content';

FIDDLE

or in jQuery:

或者在jQuery中:

$('#v65-onepage-ordercomments-value').contents().each(function() {
    if (this.nodeType===3 && this.nodeValue.trim().length) 
        this.nodeValue = 'new content';
});

FIDDLE

#2


1  

Haven't tried this but something like this should work:

没试过这个,但这样的事情应该有效:

var text = $("#v65-onepage-ordercomments-value").text();
var newText = text.replace("Order Comments:&nbsp;(Optional)", "<p>Sup?</p>");
$("#v65-onepage-ordercomments-value").text(newText); // .html(newText) is also viable.

#1


2  

It it's always a textNode that is the first child of the parent div, you can do :

它总是一个textNode,它是父div的第一个子节点,你可以这样做:

var node = document.getElementById('v65-onepage-ordercomments-value').firstChild;
node.nodeValue = 'new content';

FIDDLE

or in jQuery:

或者在jQuery中:

$('#v65-onepage-ordercomments-value').contents().each(function() {
    if (this.nodeType===3 && this.nodeValue.trim().length) 
        this.nodeValue = 'new content';
});

FIDDLE

#2


1  

Haven't tried this but something like this should work:

没试过这个,但这样的事情应该有效:

var text = $("#v65-onepage-ordercomments-value").text();
var newText = text.replace("Order Comments:&nbsp;(Optional)", "<p>Sup?</p>");
$("#v65-onepage-ordercomments-value").text(newText); // .html(newText) is also viable.