简体   繁体   English

有什么办法可以使用javascript更改文本,从而使CSS继续正常工作?

[英]Is there any way of changing the text using javascript so that the css keeps on working properly?

So basically I want to change the text in a div using javascript. 所以基本上我想使用javascript更改div中的文本。 I managed to do it, but I encountered a problem: the tag in which that text was doesn't work anymore for the javascript changed text. 我设法做到了,但遇到一个问题:该文本所在的标记不再适用于javascript更改的文本。

I tried changing .textContent to .innerHTML 我尝试将.textContent更改为.innerHTML

<div class="nr11"><h1>11</h1></div>

let lastPosition=document.querySelector('.nr'+player.lastPosition);
lastPosition.textContent=player.lastPosition;

I expect for the text ( number 11 in my case ) to be changed with player.lastPosition while still having active for player.lastPosition . 我希望文本(在本例中为11)可以通过player.lastPosition进行更改,同时仍对player.lastPosition保持活动player.lastPosition

Just change the selector to select the h1 element instead of the div : 只需更改选择器以选择h1元素而不是div

 let player = {lastPosition: 11}; let lastPosition = document.querySelector('.nr' + player.lastPosition + '>h1'); // or with a template string: `.nr${player.lastPosition}>h1` lastPosition.textContent = player.lastPosition; 
 <div class="nr11"><h1>11</h1></div> 

You are overwriting the entire <h1>11</h1> content. 您正在覆盖整个<h1>11</h1>内容。

What you want to actually do is to change the 11 inside the <h1> , so you need to select that element, instead of selecting the <div> that contains the <h1> : 您实际上想做的是更改<h1>内部的11 ,因此您需要选择该元素,而不是选择包含<h1><div> <h1>

 var player = { lastPosition: 11 }; let lastPosition=document.querySelector('.nr'+player.lastPosition+'>h1'); lastPosition.textContent=player.lastPosition; 
 <div class="nr11"><h1></h1></div> 

problem here is you are changing the <div> element text, which is: <h1>11</h1> to your new text. 这里的问题是您正在更改<div>元素文本,即: <h1>11</h1>为新文本。

This means you are replacing the whole thing instead of just the value 11 . 这意味着您正在替换整个东西,而不仅仅是值11 To solve this issue you can simply change where you are querying for the element to: 要解决此问题,您只需将查询元素的位置更改为:

let lastPosition = document.querySelector('.nr' + player.lastPosition + ' h1');
lastPosition.textContent = player.lastPosition;

This way the variable lastPosition will be the h1 element, therefore you will be changing the h1 textContent. 这样,变量lastPosition将成为h1元素,因此您将更改h1 textContent。

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

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