2012-07-18 92 views
0

一直试图看看这是多么灵活。 http://jsfiddle.net/PJSha/4/我从名称变更的get元素类名都工作,但是当我尝试用编号...有一个原因使用getelement通过id而不是名称

代码不能正常工作,并实现它:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.8.21/themes/base/jquery-ui.css" type="text/css" media="all" /> 

<input type="text" id="foo" class="bar" name="domain"> 
<div onclick="check_domain_input()">Click</div> 

<div id="dialog" title="Attention!" style="display:none"> 
    Please enter a domain name to search for. 
</div> 

<script> 
    function check_domain_input() {   
     var domain_val = document.getElementById('foo'); 

     if (domain_val[0].value.length > 0) { 
      return true; 
     } 

     $("#dialog").dialog(); 

     return false; 
    } 
</script> 

回答

3

getElementsById应该是getElementById (在Element之后没有s)。它只返回一个元素的引用,或者null

因为它返回一个引用,而不是NodeList,当您访问其value属性时,不需要[0]

+0

所以“s”与“名称”和“className”一起使用,但不与“Id”一起使用。这是否意味着在选择“名称”或“类”时可以选择多个然后一个元素? – david 2012-07-18 06:07:04

+0

更新没有s仍然不工作http://jsfiddle.net/PJSha/3/ – david 2012-07-18 06:08:29

+1

@DavidWalter你需要申请我在我的答案的第二段写的。 – alex 2012-07-18 06:11:24

0

这是要求你取的元素应该也被宣布为id="foo"

请参阅本link..a practical example

+0

它是 检查http://jsfiddle.net/PJSha/4/ – david 2012-07-18 06:12:45

+0

请检查上面的链接。 – 2012-07-18 06:20:04

+0

需要用于生成自定义提醒的代码 – david 2012-07-18 08:33:57

0

或者通过这个,

onclick="check_domain_input(this)" 

,然后让编号:

function check_domain_input(t) { alert(t.id); ... 
1

Id s在您使用ids两次的页面中使用explicitly,并且它的骑乘尝试使用不同的ID并让我知道它是否修复。

<input type="text" id="foo" class="bar" name="domain"> 
<div id="foo" onclick="check_domain_input()">Click</div> 
相关问题