[英]How to make a word a link if the user has input # before it?
我正在使用此代碼:
<form oninput="x.value=a.value">Account Info <br>
<input type="text" id="a">First Name<br>
UserName <output name="x" for="a"></output>
</form>
我希望我這樣一種方式:如果用戶輸入了一個單詞,並且他在單詞前沒有空格的地方有#
,那么該如何將該單詞作為鏈接。 表示在Facebook中發生的標簽。 可以用Java腳本以及如何完成。
這只是說明我想將這種類型集成到我的項目中作為注釋的示例。 這將與PHP。 謝謝
您可以使用textarea輸入,使用渲染顯示輸出。 然后隱藏輸入並僅顯示輸出。 但這是另一個故事。
如果使用contentEditable div,則實際上可以在同一組件中插入並呈現html。 看看這個!
$(document).on("keyup","#render", function(){
var words = $(this).text().split(" ");
console.log(words);
if (words){
var newText = words.map(function(word){
if (word.indexOf("#") == 0) {
//Starts with #
//Make a link
return $("<div/>").append($("<a/>").attr("href", "#").text(word)).html();
}
return word;
});
}
$(this).empty().append(newText.join(" "));
placeCaretAtEnd( $(this)[0]);
});
這是柱塞
感謝您的關注。
<form>Account Info <br>
<input type="text" id="a">First Name<br/>
<output id="result" name="x" for="a"></output>
<button type="button" onclick="changeVal(document.getElementById('a').value)">Click</button>
</form>
<script>
function changeVal(value1){
var dt = value1.split(" ");
document.getElementById("result").innerHTML = "";
for(var t=0; t < dt.length; t++){
if(dt[t].startsWith("#")){
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" <a href='#'>"+dt[t]+"</a>";
}
else{
document.getElementById("result").innerHTML = document.getElementById("result").innerHTML+" "+dt[t];
}
}
}
</script>
結帳Jsfiddle演示
這是一個要檢查的例子。 它可以與Enter鍵配合使用,甚至可以防止再次添加相同的標簽: http : //codepen.io/zvona/pen/KpaaMN
<input class='input' type="text" />
<output class='output'></output>
和:
'use strict';
var input = document.querySelector('.input');
var output = document.querySelector('.output');
input.addEventListener('keyup', function(evt) {
if (evt.keyCode !== 13 || !input.value.length || ~output.textContent.indexOf(input.value)) {
return;
}
var tag = document.createElement('a');
tag.appendChild(document.createTextNode(input.value));
if (input.value.startsWith("#")) {
tag.setAttribute("href", input.value);
}
output.appendChild(tag);
input.value = "";
}, false);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.