gpt4 book ai didi

javascript - 在 onchange 事件中使用 html 中的自定义数据属性

转载 作者:行者123 更新时间:2023-12-03 08:56:44 25 4
gpt4 key购买 nike

当我定义数据属性并将它们用作函数中的参数时,下面的代码给出了错误“Fieldname not Defined”。 update_person.php 使用输入字段中的属性更新数据库中的记录。有办法解决这个问题吗?

<!DOCTYPE html>

<html>
<head>
<script>

function update_person(str,fieldname,key,keyvalue)
{
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","update_person.php?q="+str+"&f="+fieldname+"&n="+key+"&nv="+keyvalue,true);
xmlhttp.send();
}
}
</script>

</head>

<body>

<form>
<input type="text" name="firstname" data-fieldname ="firstname" data-key ="PERSONID" data-keyvalue = "7" onchange = "update_person(this.value,this.data-fieldname, this.data-key,this.data-keyvalue)">
</form>
<br>
<div id="txtHint"> </div>
</body>
</html>

最佳答案

您可以使用dataset属性引用自定义数据属性:

update_person(this.value,this.dataset.fieldname, this.dataset.key,this.dataset.keyvalue)

Ref :

Reading the values of these attributes out in JavaScript is also very simple. You could use getAttribute() with their full HTML name to read them, but the standard defines a simpler way: a DOMStringMap you can read out via a dataset property.

或者使用 getAttribute() 的替代方案,格式稍长。

update_person(this.value,this.getAttribute('data-fieldname'), this.getAttribute('data-key'),this.getAttribute('data-value'))

关于javascript - 在 onchange 事件中使用 html 中的自定义数据属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32460568/

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