猿问

如何从输入字符串中使用 javascript 中的子字符串方法?

您可以使用 HTML+Javascript 从输入字符串中共享子字符串方法的解决方案吗?


<!DOCTYPE html>

<html>

<body>

<input type="text" value="test"></input>

<button onclick="myFunction()" id="testCode">Click</button>

<script>

function myFunction() {

  document.getElementById("testCode");

  var res = substring(0, 5).value;

  document.write(res);}

</script>


</body>

</html>


Cats萌萌
浏览 102回答 2
2回答

慕田峪7331174

子字符串将返回字符串的一部分。此外,添加IDon input 字段以获取值,而不是使用按钮 id 本身。请参阅以下代码段function myFunction() {&nbsp; const test = document.getElementById("testInput");&nbsp; var res = test.value.substr(0, 3);&nbsp;&nbsp;&nbsp; document.write(res);&nbsp;&nbsp;&nbsp; }<!DOCTYPE html><html><body><input type="text" value="test" id="testInput"></input><button onclick="myFunction()" id="testCode">Click</button>

慕莱坞森

substring应该在字符串变量上调用文档:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring像这样const&nbsp;test&nbsp;=&nbsp;document.getElementById('your-id') test.value&nbsp;=&nbsp;test.value.substring(0,&nbsp;6);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答