Set ASP Literal text with Javascript

2019-04-07 11:28发布

问题:

I have an asp:Literal on my page (which cannot be converted to a Label or any other control) that I need to change the text of via JavaScript. I have the following code that works for a Label. Can anybody help?

<script type="text/javascript">
        function changeText() {
            document.getElementById('<%= Test.ClientID %>').innerHTML = 'New Text';
        }
    </script>

        <a href="#" onclick='changeText()'>Change Text</a>
        <asp:Label id="Test" runat="server" Text="Original Text" />

Thanks


UPDATE: I cannot change from a literal as the code behind writes HTML/CSS to it for an Information Message e.g:

LITMessage.Text = "<div class='success'>Information Successfully Updated</div>"

回答1:

<asp:Literal> controls don't create their own HTML tag.
Therefore, there is no element that you can manipulate.

Instead, you can wrap the <asp:Literal> in a <div> tag with an ID.



回答2:

An ASP.NET Literal doesn't add any markup to the page. Therefore you have to wrap your content in some container so that you can edit it via JavaScript:

Assuming you had the following Literal on the page:

<asp:Literal runat="server" Id="literalControl" />

And were setting the text via code behind (because if you're not, you could just create the span/div in the markup to begin with and not have this issue):

literalControl.Text = "Some text you want to change";

The code behind becomes:

literalControl.Text = "<span id='myId'>Some text you want to change</span>";

And the JavaScript would be:

document.getElementById('myId').innerHTML = 'New Text';


回答3:

Does the literal contain html markup?

if not, you could wrap the literal control in a div and give it an id. Then use js to replace the text within that div.

in response to your update:

In that case, since you are rendering a div with a class of success, I would use jQuery to update the html in that div...it would be as simple as:

$('.success').html('new html goes here');


回答4:

Wrap the <asp:literal> control in a <div> and then use jQuery if needed to clear the contents like shown below:

<div id="divMyText">
  <asp:Literal ID="MyText" runat="server"></asp:Literal>
</div>

Here is how to clear the text using jQuery:

//Clear the html inside of the div
$("#divMyText").html("");


回答5:

A Literal is a direct render of text to the page. The only HTML it will render will be the HTML markup you include in the text string you set to the Literal. Instead of using a Literal surrounded by a div (unless you specifically want that functionality) you can use an ASP Label and perform operations on it.