我试图获取value或id从<a>标记中获取并在JavaScript函数中使用它.
function myFunction(qiizName, x) {
val = 1;
console.log("question number" + qiizName);
console.log("number question" + x.value);
console.log("number question" + x.id);
}
Run Code Online (Sandbox Code Playgroud)
echo"<ul>";
echo "<li><a href='#home' class='active' >module</a></li>";
$i=0;
while ( $module_row = mysqli_fetch_array($module)) {
$total=$module_row['total_question'];
$id=$module_row['id'];
echo '<li><a href="javascript:myFunction(1,this)"
id="'.$total.'"
value="'.$total.'">\''.$module_row['nom'].'\' </a></li>';
$i++;
}
echo "</ul>";
Run Code Online (Sandbox Code Playgroud)
例如:
<a href="javascript:myFunction(1,this)" id="2" value="2">cpp</a>
Run Code Online (Sandbox Code Playgroud)
我希望得到value"2"和id"2".
我在另一个项目中尝试了相同的代码并且它可以工作,但在这种情况下它根本不起作用.它在控制台中返回"undefined".
出了什么问题?
一个<a>元素没有value属性,即是无效的HTML.只有表单字段有一个value.您可以设置自定义data-属性(如下所示)并使用element.dataset属性在JavaScript中访问它.
此外,虽然现在有效的是给一个id以数字开头的元素,但这是不可取的,因为这会引起混淆并引发问题.
接下来,不要使用该href属性来嵌入JavaScript(即href="javascript:..."),当链接被点击时,启动一些JavaScript的技术大约有20年的历史,而且非常过时.如果你真的想给用户点击一些内容并且它不会导致导航,那么就不要使用它<a>,因为它会混淆屏幕阅读器,你需要取消本机click行为并且它在语义上是不正确的.几乎每个HTML元素都支持一个click事件,并且可以设置为看起来像超链接.
此外,通过将HTML与JavaScript分离,遵循现代标准和最佳实践.这一切都始于获取对您要使用的元素的JavaScript引用,并从那里开始,您可以提取或修改它的任何方面,因此您实际上不需要"传递"任何数据到您的函数将已经"绑定"到导致调用事件函数的元素,并且您可以使用this对象引用获取所需的数据.
// Get a reference to the element you wish to work with:
var element = document.getElementById("two");
// Set up event handler in JavaScript, not in the href attribute of HTML
element.addEventListener("click", myFunction);
function myFunction() {
// You have access to all of the element's attributes and child content
// via the "this" object refence because the element that caused this
// function event handler to run gets bound to "this".
console.log("ID is: " + this.id);
console.log("data-value is: " + this.dataset.value);
console.log("Content is: " + this.textContent);
}Run Code Online (Sandbox Code Playgroud)
.clickable { cursor:pointer; user-select:none; text-decoration:underline; }Run Code Online (Sandbox Code Playgroud)
<div id="two" data-value="2" class="clickable">cpp</div>Run Code Online (Sandbox Code Playgroud)