简体   繁体   中英

Why does getting value from data-attribute affect the text

I'm struggling with some syntax, mostly why the data-attribute (HTML5) is affecting the text in the way it is.

Please consider this example which does what is expected

<div id="s"></div>    

<script>

var ele = document.getElementById("s");
var txt = "this is it \n and done";
ele.innerText = txt;

</script>

The result is I see 2 lines in HTML due to the \\n . This is expected

The task means I need to change the way we work into

<div id="s" data-txt="this is it\nand done"></div>

<script>

var ele = document.getElementById("s");
var txt = ele.getAttribute("data-txt"); 
ele.innerText = txt;

</script>

Note we're now using the data attribute of data-txt . The issue is this renders the text verbatim, meaning I see 1 line: this is it\\nand done

https://jsfiddle.net/he4ydvva/

The fact I can't even use replace ( ele.getAttribute("data-txt").replace('\\n','blah'); ) suggests that although I see \\n, the computer is reading something different (maybe the charcode value or similar)

Why does this happen and how do I prevent it?

Edit

I have seen How can I insert new line/carriage returns into an element.textContent? but this won't suffice as I need the string to exist within the data-txt and concatenating as "this is " + String.fromCharCode(13) + " is not valid for HTML5

Here's what you should use:

ele = document.getElementById("t");
txt = ele.getAttribute("data-txt").replace(/\\n/g,'<br>'); 
ele.innerHTML = txt;

Explanation: The \\ char is an escape character and so to specify a new line, you need to use two \\\\ so that the 1st one escapes the meaning of the second. The second one is then treated as a normal char and is read together with the n as \\n .
Further, you must replace that with a <br> because a browser will not respect CRLF chars.

Here is your example on jsfiddle fixed: https://jsfiddle.net/4eurrzgx/

 var ele = document.getElementById("s"); var txt = "this is it \\n and done"; ele.innerText = txt; ele = document.getElementById("t"); txt = ele.getAttribute("data-txt").replace(/\\\\n/,'<br>'); ele.innerHTML = txt; 
  <div id="s"></div> <p> *** </p> <div id="t" data-txt="this is it\\nand done"></div> 

You are confusing HTML with JavaScript.

\\n is a JavaScript character. data-* attributes are HTML. For inserting newline in HTML , you should use the HTML entity &#10; (Newline) or &#13; (carriage return) or their combination.

HTML doesn't understand \\n , \\r and so on.

Also note,

<div>This is a line \n Another one</div>

This won't insert newline but the code below will:

<div>This is a line &#10; Another one</div>

Check out the full list of HTML entities

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