0

以下是我的 HTML 代码

<div id="dl_address" class="dl-row">
 <div class="dl-col1">
    <span id="dl_addressMarker" class="dl-Marker">*</span>Address:
 </div>
 <div class="dl-col2">
  <input  id="dl_addressMarker" name="p.streetAddress" maxlength="100" size="15"  
                            class="landing-qualpanel-input-standin" type="text" onClick="formOpt(id)" value="Home Address">
 </div>
</div>

以下是我的javascript代码

<script language="javascript" type="text/javascript">
function formOpt(x){

    var y=document.getElementById(x).value;
    alert(y);
    }
</script>

我不明白为什么我会变得未定义。请帮助。提前致谢

4

3 回答 3

3

那是因为您有两个具有相同 ID 的元素,这在 HTML 中是不允许的,这使得您的函数无法以这种方式获取输入。

更改您输入的ID,您会没事的。

您可以通过传递元素而不是 id 来简化代码:

HTML:

<input  id="dl_addressMarker2" name="p.streetAddress"
      maxlength="100" size="15"  
      class="landing-qualpanel-input-standin" type="text"
      onClick="formOpt(this)" value="Home Address">

JavaScript:

function formOpt(x){
   var y = x.value;
   alert(y);
}
于 2013-02-03T11:53:25.627 回答
2

你有2个问题。(1)你应该像这样调用你的方法: formOpt(this)它将传入当前元素。(2)你有重复的 DOM id。

写法是这样的:

<script language="javascript" type="text/javascript">
function formOpt(x){
    //x is now the input element. You can fetch its id property.
    var y=document.getElementById(x.id).value;
    // you can do other things with x also.
    alert(y);
    }
</script>
<div id="dl_address" class="dl-row">
 <div class="dl-col1">
    <span id="dl_addressMarker" class="dl-Marker">*</span>Address:
 </div>
 <div class="dl-col2">
 <!-- I renamed the id on the input -->
  <input  id="dl_addressMarker_input" name="p.streetAddress" maxlength="100" 
  size="15"  class="landing-qualpanel-input-standin" 
 <!-- pass this into the function -->
  type="text" onClick="formOpt(this);" value="Home Address">
 </div>
</div>

请参阅工作示例:http: //jsfiddle.net/KXCeh/1/

于 2013-02-03T11:55:24.207 回答
1

您需要传递 id 的值,并且您还需要为每个元素保持唯一的 id

            <div class="dl-col2">
  <input  id="dl_addressMarker" name="p.streetAddress" maxlength="100" size="15"  
                            class="landing-qualpanel-input-standin" type="text" onClick="formOpt('dl_addressMarker')" value="Home Address">
 </div>
于 2013-02-03T11:53:38.077 回答