简体   繁体   中英

Javascript - I can't make the “this” keyword on my html

This is currently my simplified code and it's not working. What I would like to do is to have two input(id's nono1 and nono2) calling the same function(nonoto). I cant use document.getElementById() because they different ID's.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<script language="javascript" type="text/javascript">
    function nonoto()
    {
         alert(document.getElementById(this.id).value);
    }
</script>
</head>

Whenever you use nonoto function, pass current input element object as this :

<input id="one" onchange="nonoto(this)" >

and function will become:

function nonoto(obj)
{
     alert(obj.value);
}

So the function doesn't have to know any ids to get element value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM