Javascript 将 .val() 转换为字符串 jQuery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11043825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a .val() into string jQuery
提问by SimonBASS
I have a jQuery function that gets the value from a form input text object named content
in which a user can enter an HTML tag in the form. For example, the user types "Sample" with <b>
tags. Once submit is fired, jQuery gets the value from content
.
我有一个 jQuery 函数,它从一个名为的表单输入文本对象中获取值,content
用户可以在其中输入一个 HTML 标记。例如,用户输入带有<b>
标签的“Sample” 。一旦提交被触发,jQuery 就会从content
.
var content = $('[name=content]').val();
My problem is if the user has a tag lets say a <b>
tag, I want to output the raw html string to the user instead of having it rendered.
我的问题是,如果用户有一个标签可以说是一个<b>
标签,我想将原始 html 字符串输出给用户而不是呈现它。
How can I do it? Any help will be much appreciated, I'm new to jQuery.
我该怎么做?任何帮助将不胜感激,我是 jQuery 的新手。
回答by SLaks
.val()
already returns a string.
You're asking how to display that string without parsing it as HTML.
.val()
已经返回一个字符串。
您问的是如何在不将其解析为 HTML 的情况下显示该字符串。
Call .text()
.
打电话.text()
。
回答by Crayon Violent
Okay, so it sounds like you are wanting to display the code without the browser rendering it. Perhaps you want to convert your tags to html enttities
好的,听起来您希望在浏览器不渲染的情况下显示代码。也许您想将标签转换为 html 实体
回答by RobG
Without jQuery, you would do:
如果没有 jQuery,你会这样做:
document.getElementsByName('content')[0].value;
to get exactly the stirng that the user entered.
以获得用户输入的确切信息。
Edit
编辑
Now I get it, you are writing the value as the innerHTML of another element and you want the literal text displayed, not the markup. So continuing with a sans-jQuery example:
现在我明白了,您正在将值写入另一个元素的 innerHTML,并且您希望显示文字文本,而不是标记。因此,继续使用 sans-jQuery 示例:
<script>
// Set the text content of an element
var setText = (function() {
var d = document.createElement('div');
if (typeof d.textContent == 'string') {
d = null;
return function(el, text) {
el.textContent = text;
};
} else if (typeof d.innerText == 'string') {
d = null;
return function(el, text) {
el.innerText = text;
};
}
}());
</script>
<input name="content">
<button onclick="
setText(document.getElementById('d0'),
document.getElementsByName('content')[0].value);
">get value</button>
<div id="d0"></div>
Or as SLaks suggests (rather cryptically):
或者正如 SLaks 建议的那样(相当神秘):
$('#d0').text($('[name=content]').val());
Though I don't know why it wasn't in his or her answer.
虽然我不知道为什么这不在他或她的回答中。
回答by Jongab
I was also having this problem. I fixed it using the following cheat:
我也遇到了这个问题。我使用以下作弊修复了它:
var val = $("#item").val() + "";