why is ® not working when used with jquery

2019-09-09 20:46发布

问题:

I am having a problem I want to attach the registered trademark symbol a button and I want it to be done with jquery because there are lots and lots of buttons that require the sign when I used it with html for example(below) it worked.

<input type="button" class="button_a" value="Value &reg;" />

But when I used jquery as below it returns as plain text:

$('.button_a').each(function(){
    $(this).attr("value",$(this).attr("value")+" &reg;");
});

I don't want to waste my time and space by putting &reg; in all the button's values so I want it to be done in jquery but what am I doing incorrect.

I know it's a sluggish question but please someone help out me in this question

Javascript may be also used.

For more info please comment and ask

Thanks....

回答1:

&reg; is being rendered as a text string, but you can use unicode \u00AE

$('.button_a').each(function(){
    this.value = this.value +" \u00AE";
});

http://jsfiddle.net/fbuohvm1/

or just ®:

$('.button_a').each(function(){
    this.value = this.value +" ®";
});

http://jsfiddle.net/fbuohvm1/1/



回答2:

Because, while the DOM you are manipulating was initialised from an HTML document, you are now dealing with DOM and not HTML. You are writing the value as text not as HTML.

You need to use either a literal character ("®") or a JavaScript escape sequence ("\u00AE").



回答3:

You have to encode it first before setting the value of textbox.

$('.button_a').each(function () {

    $(this).val("value " + $("<div/>").html('&reg;').text());
});

$("<div/>").html('&reg;').text() will return the encoded value.

Demo: https://jsfiddle.net/tusharj/t2gwptys/



回答4:

you need to process content by html(), because html entities is manipulate by html() function, try this code.

$('.button_a').each(function(){
    $(this).val($("<p/>").html($(this).val()+" &reg;").html());
});


回答5:

Use a hidden div.

$('.button_a').each(function(){
    var decoded = $('<div/>').html('&reg;').text();
    $(this).val($(this).val() + ' ' + decoded);
});

See Sample



回答6:

In your case plain js is more straightforward:

$('.button_a').each(function(){
    this.value += " &reg;";
});

-- EDIT -- Unfortunately this is still escaped, in fact you need

    this.value += " \u00AE";