简体   繁体   中英

JS: Replace a link with a link. And that link with a link

I am going to make a block of text, such that if you click on a word, it is replaced by a lexical substitute.

Eg ''fearful-of-cats'' is a lexical substitute for ''ailurophobic'', because if you replace the latter with the former in any text, the meaning does not change.

However, I am having trouble with the function required to replace innerHTMLs of elements, even at this early stage.

Here is an example, and rough idea, of what the function looks like:

<!DOCTYPE html>
<html>
<body>
<p><a href="#" id="Test_1" onclick=" replace(id,'Replacement 1') ">Test 1</a></p>
<p><a href="#" id="Test_2" onclick=" replace(id,'Replacement 2') ">Test 2</a></p>

<script>
function replace(x, y) {
    document.getElementById(x).innerHTML = y;
}
</script>
</body>
</html> 

(That works when I save it to my Desktop as an .html file, but not on jsfiddle for some reason (otherwise I would link you to it.))

I would like you to show me the code revised, such that if I click on "Test 1", I get "Replacement 1". And then if I click on "Replacement 1", I get "ReReplacement 1".

The problem I currently have is to do with escape characters, I believe.

So, I would appreciate if your answer could shed light on where I may be going wrong with this in general. Thanks.

***EIDT***

Either this or the other works

<a href="#" id="Test_1" onclick=" replace('Test_1','Replacement 1') ">Test 1</a>

I got this to work, though to be fair even with your base code I could never get the same error you speak of. I'm using the data-replaced attribute to determine whether or not the replace has been called already. I added a third parameter just in case the string will be changed later on. If not,whereever you see prefix , just change it with the string literal you want to use.

 <body> <p><a href="#" id="Test_1" onclick=" replace(this.id,'Replacement 1','Re') ">Test 1</a></p> <p><a href="#" id="Test_2" onclick=" replace(this.id,'Replacement 2','Re') ">Test 2</a></p> <script> function replace(x, y, prefix) { var el = document.getElementById(x); var replace_text = y; if(el.getAttribute('data-replaced')!=='true'){ el.setAttribute('data-replaced',true); }else{ replace_text = prefix+el.innerHTML; } el.innerHTML = replace_text; } </script> </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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