简体   繁体   English

在 Vanilla Javascript 中自动结束 html 标签

[英]Auto end html tags in Vanilla Javascript

The user enters a tag (like <div> ), and JavaScript should end it ( </div> ).用户输入一个标签(如<div> ),JavaScript 应该结束它( </div> )。 It should also not do it for HTML tags like <hello> .对于像<hello>这样的 HTML 标签,它也不应该这样做。

I've tried str. repeat我试过str. repeat str. repeat , but it didn't come out as expected. str. repeat ,但它没有按预期出现。 This is what I've tried:这是我尝试过的:

 function inputtextarea() { let inputtextarea = document.getElementById('inputtextarea'); inputtextarea.value = inputtextarea.value.repeat(2); }
 <textarea name="inputtextarea" id="inputtextarea" cols="30" rows="10" oninput="inputtextarea()"></textarea>

Can you tell me why it is not working?你能告诉我为什么它不起作用吗?

link for str.repeat str.repeat链接

This is my attempt, with some work you should get something better.这是我的尝试,通过一些工作你应该会得到更好的东西。

Fixed some errors!修正了一些错误!

 function checkKeypress(elem, evt) { var txtBef = elem.value.slice(0, elem.selectionEnd); var txtAft = elem.value.slice(elem.selectionEnd, elem.value.lenth); var lastString = txtBef .replace(/\\s+/g, " ") /*replace multiple spaces to just one*/ .split(" "); lastString = lastString[lastString.length - 1]; if(evt.key == ">"){ if(lastString.includes("<")){ var addClose = lastString.replace(/[< >]/g, ""); //replaces < and > to blank space elem.value = txtBef+" </"+addClose+">"+txtAft; //closes the writed tag elem.selectionEnd = txtBef.length + 1; //places the cursor at the midle of the tags } } }
 textarea { width: 100%; height: 100px; }
 Write a existing or a custom HTML tag and this textarea will altomatically close it for you! <textarea onkeyup="checkKeypress(this, event)"></textarea>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM