简体   繁体   English

如何从HTML的内部文本中删除(仅)星号 <td> 零件?

[英]How do I remove (only) an asterisk from the inner text of an HTML <td> component?

I'm trying to figure out how to remove/replace an "asterisk" from the innerHTML of a <td> component. 我试图弄清楚如何从<td>组件的innerHTML中删除/替换“星号”。

I have a which contains same free text and an input control. 我有一个包含相同的自由文本和输入控件。 Assume in the following sample that <td> == this 在以下示例中假定<td> == this

$(this)[0].innerHTML
"*&nbsp;<input name="ctl00$MainContent$TxnDate" type="text" id="TxnDate" class="DetailTextBox dvFieldTypeDateTime dvRequiredField hasDatepicker validationFailed" style="width:250px;">&nbsp;Required Field"

How do I replace/remove the asterisk from the inner HTML? 如何从内部HTML替换/删除星号?

$(this)[0].innerHTML[0]

I have tried: 我努力了:

$(this)[0].innerHTML.replace(/\*/g, '');

But that seems to delete the current contents of my input control. 但这似乎删除了我输入控件的当前内容。

The regular expression you have is correct, you need to assign the changed html back to the innerHTML , check it here 您拥有的正则表达式是正确的,您需要将更改后的html分配回innerHTML在此处进行检查

this.innerHTML = this.innerHTML.replace(/\*/g, '');

After assigning the changed html back you wont get * 在分配了更改的html后,您将不会得到*

Live Demo 现场演示

Edit 编辑

If you want to replace only in first node ie *&nbsp; 如果您只想替换第一个节点,即*&nbsp; then you only need firstChild 那你只需要firstChild

Live Demo 现场演示

firstChild = this.firstChild;
firstChild.nodeValue = firstChild.nodeValue.replace(/\*/g, '');

To exclude the input you can use nodeType to apply the replace on only text elements those are child of the html element you have by iterating through the childs. 要排除输入,您可以使用nodeType通过在子元素上进行迭代来仅对属于html元素子元素的文本元素应用替换。

Live Demo 现场演示

function removeAsterisk(htmlParentObject)
{
    nextsib = htmlParentObject.firstChild;
    while(nextsib != null)
    {
        if(nextsib.nodeType === 3);
              nextsib.nodeValue = nextsib.nodeValue.replace(/\*/g, '');
        nextsib = nextsib.nextSibling;    
    }
}

当您使用jQuery时,您可以这样说

$(this).eq(0).html($(this).html().replace(/\*/g, ''))

Try this example: 试试这个例子:

script 脚本

var ps = document.getElementsByTagName('p');
var l = ps.length;
if (l--) do {
    ps[l].innerHTML = ps[l].innerHTML.replace(/\*/g, '');
} while (l--);

html HTML

<p>hi there*, everyone* !</p>
<p>LOL* !</p>

output 产量

hi there, everyone !

LOL !

try this solution: 试试这个解决方案:

$('td.validationFailed').contents().filter(function() { 
    return this.nodeType == 3 && this.wholeText.indexOf('*') > -1; 
})
.remove();

Working Demo 工作演示

Via user3558931 通过user3558931

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM