在onchange事件中使用html中的自定义数据属性 [英] Using custom data-attributes in html in onchange event

查看:113
本文介绍了在onchange事件中使用html中的自定义数据属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

The code below gives me an error "Fieldname not defined" when I am defining data-attributes and using them as parameters in a function. The update_person.php is updating a record in a database using the attributes in the input field. Is there a way to work around this?

<!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>

推荐答案

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

You can refer to a custom data attribute using the dataset property:

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

参考


在JavaScript中读取这些属性的值也非常简单。您可以使用带有完整HTML名称的getAttribute()来读取
,但标准定义了一种更简单的方法:DOMStringMap可以通过数据集属性读取

或使用 getAttribute()的替代和略长的格式。

Or the alternative, and slightly longer format using getAttribute().

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

这篇关于在onchange事件中使用html中的自定义数据属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆