function test(){
let cart1 = document.getElementById('cart1');
console.log(cart1);
}
我創建了一個測驗函式來將<p>標簽內的內容列印到控制臺上。
這是我的 HTML。
<body>
<p id="cart1">
hello world
</p>
<script src="home.js"></script>
</body>
</html>
但這是列印在控制臺上的內容:
空值
為什么會這樣?
uj5u.com熱心網友回復:
只需Home.js像這樣編輯你。
function test() {
let cart1 = document.getElementById('cart1');
console.log(cart1);
}
test();
<p id="cart1">
hello world
</p>
uj5u.com熱心網友回復:
請將您的 JS 代碼替換為以下內容。您必須使用 innerHTML 屬性從 p 標簽中獲取文本。innerHTML 屬性設定或回傳元素的 HTML 內容(內部 HTML)。
test();
function test(){
let cart1 = document.getElementById('cart1').innerHTML;
console.log(cart1);
}
uj5u.com熱心網友回復:
我無法重現這個問題,我寫了一個簡單的例子,它作業正常。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="cart1">hello world</p>
</body>
<script type="text/javascript">
function test() {
let cart1 = document.getElementById('cart1');
console.log(cart1);
}
test();
</script>
</html>
如果他仍然有問題,我建議使用該onload事件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p id="cart1">hello world</p>
</body>
<script type="text/javascript">
window.onload = () => {
let cart1 = document.getElementById('cart1');
console.log(cart1);
}
</script>
</html>
uj5u.com熱心網友回復:
我認為你應該做 console.log(cart1.innerHTML);
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/358783.html
標籤:javascript html 网络
