简体   繁体   English

JavaScript替换无效

[英]Javascript replaces didn't work

I'm trying to replace a part of my HTML code with JS but doesn't work. 我试图用JS替换我的HTML代码的一部分,但是不起作用。

I have the next code: 我有下一个代码:

<td id="one"><a href="servlet.jsp?account='old'" >old</a></td>

And i'm want to change "old" for "new", like this: 我想将“旧”更改为“新”,如下所示:

<td id="one"><a href="servlet.jsp?account='new'" >new</a></td>

Then i'm using JS because i need to do with this using the method replace(), then, my JS is: 然后我使用了JS,因为我需要使用方法replace()来完成此操作,然后,我的JS是:

var old = "old";
var rep = "new";
var elem = document.getElementById("one");
var text = elem.innerHTML;
text = text.replace(old,rep);
elem.innerHTML = text;

I tryed and search but always i founded the same. 我尝试搜索,但始终都建立了相同的名字。

Any suggestion are welcome. 任何建议都欢迎。

(I wrote the cody by memory because i'm not in the office and it's more complex) i'll try tomorrow) (我以记忆的方式写了科迪,因为我不在办公室,而且更复杂)明天我会尝试)

Because "new" is a reserved word in JavaScript. 因为“新”是JavaScript中的保留字。

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words 请参阅: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words

No clue - it works for me. 毫无头绪-它对我有用。 However, your method is very insecure; 但是,您的方法非常不安全; instead of working on elem.innerHTML , it would be much better to use elem.getAttribute and elem.setAttribute for direct access to href . elem.innerHTML ,不如使用elem.getAttributeelem.setAttribute直接访问href会更好。 Otherwise, imagine what would happen if your old happens to be "ref" , or something similar that coincidentally exists before your intended term... 否则,想象一下,如果您的old碰巧是"ref" ,或者在您打算的任期之前偶然存在的类似东西,将会发生什么...

EDIT: doh, didn't even notice the var name >.< 编辑:哎呀,甚至都没有注意到var名称>。<

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

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