使用id而不是name的getelement

时间:2012-07-18 06:03:25

标签: jquery

试图看看这有多灵活。 http://jsfiddle.net/PJSha/4/我已经将get元素从Name更改为ClassName,当我尝试用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>

4 个答案:

答案 0 :(得分:3)

getElementsById应该是getElementByIds之后没有Element)。它只返回对一个元素的引用,或null

因为它返回引用而不是NodeList,所以当您访问其[0]属性时,value不是必需的。

答案 1 :(得分:1)

Id在您正在使用ID两次的页面中使用explicitly并且过度使用不同的ID并让我知道它是否已修复。

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

答案 2 :(得分:0)

您要获取的元素也必须使用id="foo"

声明

请参阅此链接..a practical example

答案 3 :(得分:0)

或通过这个,

onclick="check_domain_input(this)"

然后获取id:

function check_domain_input(t) { alert(t.id); ...
相关问题