3 回答

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
發(fā)生這種情況是因?yàn)?lt;p>您擁有的標(biāo)簽沒有內(nèi)容。如果您將文本添加到<p>并雙擊該文本,它將起作用。
解決方案是使用div而不是p:
function getID() {
var x = document.getElementsByClassName("blueblock")[0].id;
document.getElementById("xx").innerText = x;
}
.blueblock {
width: 30%;
height: 50vh;
float: left;
background-color: lightblue;
text-align: justify;
overflow: auto;
}
<div id="xx" ondblclick="getID()">
<div class="blueblock" id="bluebl">
<p>Just some text inside of the block.</p>
</div>
</div>

TA貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
第一個(gè) p 元素基本上由下一個(gè) div 元素終止,因?yàn)?ap(等效段落)不能包含 div。因此,看不到雙擊代碼,因?yàn)閷?shí)際上第一個(gè) p 元素沒有內(nèi)容。
將 p 元素替換為 div 并正確終止,意味著 div 中的任何內(nèi)容都會(huì)導(dǎo)致看到雙擊。
但是,請(qǐng)注意,并非所有瀏覽器都支持 ondblclick,因此我們通過使用 Javascript 將事件偵聽器添加到元素來替換它。
這是完整的片段。請(qǐng)注意,當(dāng)您雙擊時(shí),innerHTML 會(huì)被替換,因此如果您再次雙擊,您將在瀏覽器控制臺(tái)中看到錯(cuò)誤,因?yàn)闊o法找到該元素 - 它不再存在。
<!DOCTYPE html>
<html>
<head>
? <title>Test</title>
? <script>
? ? function getID() {
? ? ? var x = document.getElementsByClassName("blueblock")[0].id;
? ? ? document.getElementById("xx").innerHTML = x;
? ? ? }
? </script>
? <style>
? ?.blueblock {
? ? ? width: 30%;
? ? ? height: 50vh;
? ? ? float: left;
? ? ? background-color: lightblue;
? ? ? text-align: justify;
? ? ? overflow: auto;
? ?}
? </style>
</head>
<body>
<div id="xx">
? <div class="blueblock" id="bluebl">
? ? <p>Just some text inside of the block.</p>
? </div>
? </div>
<script>
? document.getElementById('xx').addEventListener('dblclick',getID);
</script>
</body>
</html>

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
您需要具有有效的 html 元素嵌套,并且您可能應(yīng)該適應(yīng)這些部分中的多個(gè)部分。這是一個(gè)例子。
function getID(el) {
var x = el.getElementsByClassName("blueblock")[0].id;
document.getElementById(el.id).innerHTML = x;
}
.blueblock {
width:30%;
height:50vh;
float:left;
background-color:lightblue;
text-align:justify;
overflow:auto;
}
<div id="xx" ondblclick="getID(this)">
<div class="blueblock" id="bluebl">
<p>Just some text inside of the block.</p>
</div>
</div>
<div id="xx2" ondblclick="getID(this)">
<div class="blueblock" id="bluebl2">
<p>Just some more text inside of the block.</p>
</div>
</div>
添加回答
舉報(bào)