gpt4 book ai didi

javascript - 从 id 获取值并将其传递给函数

转载 作者:行者123 更新时间:2023-11-28 14:56:38 25 4
gpt4 key购买 nike

有谁知道我在哪里犯了错误?

function functionTest(name) {
var Name = name;
alert(Name);

}
<h3 id="name" value="testingName"><a href="#"> test </a></h3>
<button onclick="functionTest(document.getElementById('name').value)"></button>

输出未定义

最佳答案

<h3>元素没有 value属性。但你可以使用data-*属性来代替。像这样的事情:

<h3 id="name" data-value="testingName">

然后您可以从 dataset 访问它属性:

document.getElementById('name').dataset.value

Example ,使用您的原始代码

function functionTest(name) {
var Name = name;
alert(Name);
}
<h3 id="name" data-value="testingName"><a href="#"> test </a></h3>
<button onclick="functionTest(document.getElementById('name').dataset.value)"></button>

关于javascript - 从 id 获取值并将其传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42633321/

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