<p>
无法进入 'but
is valid. Also,
getElementsByClass()is invalid. It should be
getElementsByClassName()`。 F12 开发者工具中的控制台应该会告诉您这一点。
因此,将您的 HTML 更改为:
<button onclick="copyText()">
<div class="copy">Address line 1</div>
<div class="copy">Address line 2</div>
<div class="copy">Address line 3</div>
<div class="copy">County</div>
<div class="copy">Post code</div>
</button>
并在 JS 中更改这一行:
var copyText = document.getElementsByClassName("copy");
然后,
copyText
没有按钮本身的文本。它包含在 contentText
或 innerText
属性中
for (let i = 0; i < copyText.length; i++) {
text += copyText[i].contentText + "<br>";
}
不清楚你在这里想做什么,但它是无效的,因为
text
是一个变量,而不是你可以调用像 .select()
这样的函数。
// Select the text field
text.select();
text.setSelectionRange(0, 99999); // For mobile devices
我只是评论了上述内容,因为您不需要它来实现您所描述的目标。
要获取您要查找的内容,只需使用
text
而不是 text.value
。因此,例如:
alert("Copied the text: " + text);