将第一和第二个字符的值存储在两个不同的真实中



我希望先存储&使用 ccMain的两个不同变量id中的值的第二个字符。使用jQuery或JavaScript。

这是我必须设置环境的HTML代码:

<span id="ccMain">GM</span>

使用普通JavaScript,您可以使用字符串对象的"子字符串"方法检索特定字符。请参阅MDN字符串:: substring

var main = document.getElementById("ccMain");
var text = main.innerText;
console.log("First Letter: " + text.substring(0,1));
console.log("Second Letter: " + text.substring(1,2));
<div id="ccMain">Simple Text</div>

由于您只需要第一个和第二个字符,因此您可以将索引用作01来获得第一个和第二个值。

var str = $('#ccMain').text();
var first = str[0];
var second = str[1];
console.log(first," ", second)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="ccMain">GM</span>

最新更新