属性是否由setAttribute函数中的id自动获取?

时间:2016-07-07 18:50:57

标签: javascript

的JavaScript

function billingFunction() {
 if(document.getElementById('same').checked) {
  document.getElementById('billingName').setAttribute('value', shippingName.value);
 }
}

HTML

<html>

<head>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<h1>JavaScript Homework</h1>
    <p>Add the JavaScript code needed to enable auto-complete on this form.  Whenever the checkbox is checked, the code should automatically copy the values from Shipping Name and Shipping Zip into the Billing Name and Billing Zip.  If the checkbox is unchecked, the Billing Name and Billing Zip should go blank.</p>

<form>
        <fieldset>
            <legend>Shipping Information</legend>
            <label for ="shippingName">Name:</label>
            <input type = "text" name = "shipName" id = "shippingName" required><br/>
            <label for = "shippingzip">Zip code:</label>
            <input type = "text" name = "shipZip" id = "shippingZip" pattern = "[0-9]{5}" required><br/>
        </fieldset>
        <input type="checkbox" id="same" name="same" onchange= "billingFunction()"/>
        <label for = "same">Is the Billing Information the Same?</label>

        <fieldset> 
            <legend>Billing Information</legend>
            <label for ="billingName">Name:</label>
            <input type = "text" name = "billName" id = "billingName" required><br/>
            <label for = "billingzip">Zip code:</label>
            <input type = "text" name = "billZip" id = "billingZip" pattern = "[0-9]{5}" required><br/>
        </fieldset>
            <input type = "submit" value = "Verify"/>
        </form>
        <script src="autocomplete.js"></script>
</body>     
</html> 

我刚看到这个例子。你能帮我理解为什么我们必须使用getElementById获取具有“相同”id的元素,而shippingName.value按原样工作(没有getElementById)。 shippingName不是全局变量。

该功能有效。至少在Chrome和Firefox中。

整个例子。 http://codepen.io/Kifsif/pen/EyvLXq

0 个答案:

没有答案