【问题标题】:javascript trouble with the setattributefunctionsetattribute函数的javascript问题
【发布时间】:2012-09-27 11:58:17
【问题描述】:

我使用的表单会根据您单击单选按钮的哪个选项来显示一些 div。

问题是 div 设置为不显示,除非我选择一个选项。

所以我添加了以下函数,以确保如果显示 div,它将具有具有所需属性的表单。

所以我给出了这个函数:

<script type="text/javascript">
function addattribute()
{
    if (document.getElementById('montant').style.display == "block")
    {
        document.getElementsByName('montant_creance').setAttribute('required');
        document.getElementsByName('condition2').setAttribute('required');
    }
    if (document.getElementById('montant').style.display == "none")
    {
        document.getElementsByName('montant_creance').setAttribute('required','false');
        document.getElementsByName('condition2').setAttribute('required','false');
    }
}
</script>   

但它在控制台中对我说:

Uncaught TypeError: Object #&lt;NodeList&gt; has no method 'setAttribute'

我真的不知道如何找到问题。

接受我最大的尊重。

亲切的问候。

SP。

【问题讨论】:

    标签: javascript html function setattribute


    【解决方案1】:

    getElementsByName返回一个元素的集合,所以你要写e.g.

    document.getElementsByName('montant_creance')[0].setAttribute('required');
    

    每次使用此方法(或类似方法,如getElementsByTagNamegetElementsByClassName...)时使用正确的索引

    【讨论】:

    • 非常感谢,我把你告诉我的都写了;现在它对我说 Name='condition2' 的无效表单控件不可聚焦。
    • 如果您觉得这个问题与您的原始问题无关,您应该打开一个新的讨论并发布一些代码以在演示页面 /fiddle/jsbin 中查看,否则只需发布一个包含一些代码的链接跨度>
    • 实际上它可以工作,只是当我点击返回第一个选项并且 div 设置为不显示时,它会显示此消息。
    【解决方案2】:

    setAttribute 有两个参数名称和值:

    setAttribute('name','value');
    

    【讨论】:

    • 尊敬的先生,这就是我写的 setAttribute('required','false');
    • 我有这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多