我已经为autosuggest写了一个javascript代码。我正在获取autosuggest.but当我选择任何autosuggested word.it将带有这样的html标签。:
如果我在文本框中输入“w”。然后我得到一些自动提出的单词如果我选择那个单词然后在文本框中它会像 w water, w 等等。
下面是我的代码。:
<html>
<head>
</head>
<body>
<input name="txt" type="text" id="new"
placeholder="Please key in some text.">
<script type="text/javascript" src="autoComplt.js"></script>
<script>
var words =[];
function get_words(q,calbk)
{
var xmlhttp = new XMLHttpRequest();
var url = "http://xxxx.poc.yyyyy.com/v1/xxx/suggest?authKey=baef7f8e39c53t6990f852c8a14b7f6018b58&q="
+ q + "&rows=8";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = JSON.parse(xmlhttp.responseText);
var items = data.suggestions;
var words = items.map(function(item){return item.suggestion;});
console.log(words);
calbk(words)
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
var input = document.querySelector("input[name=txt]");
autoComplt.enable(input, {
hintsFetcher : function(v, openList) {
console.log("in")
get_words(v,openList)
}
});
</script>
</body>
</html>
如何从文本框中删除该html标记。
答案 0 :(得分:1)
您可以将HTML字符串插入到DOM元素中,然后再将文本要求退出,从而将HTML字符串转换为文本。这将适用于更老版本的IE:
function stripHTML(html) {
var div = document.createElement("div");
div.innerHTML = html;
return div.textContent || div.innerText;
}
答案 1 :(得分:0)
您可以使用DOMParser API:并查找返回结果的textContent:
var words = ["<b>w</b>hite out", "<b>w</b>ireless mouse", "<b>w</b>hite board", "<b>w</b>ater", "<b>w</b>ireless keyboard", "<b>w</b>ireless router", "<b>w</b>ireless printers", "<b>w</b>indow envelopes"]
var p = new DOMParser().parseFromString(words[Math.floor(Math.random()*words.length)], 'text/html').documentElement.textContent;
document.body.textContent = p;
( ps :在Math.floor(Math.random()*words.length)
函数中点击时调用{更改clbk()
。)