gpt4 book ai didi

javascript - 在 HTML 页面中使用 javascript 函数

转载 作者:行者123 更新时间:2023-11-28 10:40:20 26 4
gpt4 key购买 nike

我已经在互联网上搜索了我的问题的答案,但没有找到。

当我尝试在简单的 HTML 页面中使用 javascript 函数(例如:substring、lastIndexOf 等)时,出现错误。

作为示例,请参阅以下 HTML 页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type = "text/JavaScript" language="JavaScript">
function redirect()
{
var URL = window.location;
alert(URL.lastIndexOf("/"));

}
</script>
</head>
<body onload="javascript: redirect();">
</body>

错误如下:

Javascript Error

我该如何解决这个问题?

提前致谢,

马塞洛·卡马拉特

最佳答案

window.location具有所有这些属性和方法......并且不是字符串,因此您不能使用那些用于字符串的方法。

window.location

因此您需要使用它的属性之一,例如 href,它是一个实际的字符串。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type = "text/JavaScript" language="JavaScript">
function redirect()
{
var URL = window.location.href;
alert(URL.lastIndexOf("/"));

}
</script>
</head>
<body onload="javascript: redirect();">
</body>

关于javascript - 在 HTML 页面中使用 javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52706086/

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