gpt4 book ai didi

javascript - 使用 GetElementById 传递多个值(在特定字符后拆分)

转载 作者:行者123 更新时间:2023-11-30 11:23:13 25 4
gpt4 key购买 nike

我几乎没有 JavaScript 经验,但我知道 getElementID 只携带一个值,所以我怎么能传递 2 个值?我可以像下面那样使用它两次,还是使用另一种 GetElementBy/GetElementsBy 方法更好?

<script type="text/javascript">
$(document).ready(function () {
hash();
function hash() {
var hashParams = window.location.hash.substr(1).split('&');
for (var i = 0; i < hashParams.length; i++) {
var p = hashParams[i].split('=');
document.getElementById("<%=start.ClientID%>").value = decodeURIComponent(p[1]);
document.getElementById("<%=end.ClientID%>").value = decodeURIComponent(p[1]);;
}

}
});
</script>

编辑因此,我决定使用循环两次并使其正常工作,但我传递的值包含我需要删除的文本。有没有办法可以在某个 Angular 色之后切断拆分?这是我的新代码

<script type="text/javascript">

$(document).ready(function () {
hash();
function hash() {
var hashParams = window.location.hash.substr(1).split('#');
for (var i = 0; i < hashParams.length; i++) {
var p = hashParams[i].split('=');
document.getElementById("<%=start.ClientID%>").value = decodeURIComponent(p[1]);
}
var hashParams = window.location.hash.substr(1).split('&');
for (var i = 0; i < hashParams.length; i++) {
var p = hashParams[i].split('=');
document.getElementById("<%=end.ClientID%>").value = decodeURIComponent(p[1]);;
}

}
});
</script>

这是从上一页转发时出现在搜索栏中的文本。localhost:56363/Bookings.aspx#start=27/02/2018 12:30&end=27/02/2018 17:30

开始和结束输入框填充了值,但开始输入框 (27/02/2018 12:30&end) 有我要 chop 的字符 (&end)。有没有办法在某个字符后停止拆分?

最佳答案

使用它两次是完全可以接受的。而且,如果它们是分开的东西,那么它就有意义了。

虽然您也可以使用 getElementsByTagName()getElementsByName()getElementsByClassName(),但通常使用 document.querySelectorAll( ) 是更现代的选择。

如果他们有一些共同点(比如类),你可以这样使用它:

const nodeList = document.querySelectorAll('.classToGet');
Array.prototype.forEach.call(nodeList, element => element.value = decodeURIComponent(p[1]));

document.querySelectorAll()(以及 getElementsBy 函数)返回一个 NodeList,有点像 Array,但没有 Array 的函数,所以你需要 Array.prototype.forEach.call() 来循环它们。

document.querySelectorAll() 接受您提供给 CSS 的字符串,并且 NodeList 具有匹配该字符串的所有元素。

仅供引用,有一个等效的 document.querySelector() 获取单个元素,因此您可以将它用于 ID:

document.querySelector("#<%=start.ClientID%>")

注意 #,就像您在开头使用 CSS 一样。

关于javascript - 使用 GetElementById 传递多个值(在特定字符后拆分),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49017294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com