IE的getElementsByName有问题

Yes, it does.

是的,它确实。

Sometimes it's convenient to use "HTML arrays", meaning to name fields like: <input name="something[]" />

有时使用“ HTML数组”很方便,这意味着使用以下字段来命名: <input name="something[]" />

Then on the server side you loop through the array $_POST['something']

然后在服务器端,您遍历数组$_POST['something']

This allows for a flexibility where your app doesn't know the number of inputs in advance, but works fine regardless of the actual number.

这样可以提供灵活性,使您的应用程序不预先知道输入数量,但是无论实际数量如何都可以正常工作。

Even cooler is that you can generate fields on the client-side, with JavaScript.

更酷的是,您可以使用JavaScript在客户端生成字段。

The problem is if you want to do some sort of client-side validation after you've generated fields on the fly. If you have:

问题是,您想动态生成字段后是否要进行某种客户端验证。 如果你有:

<input name="something[]" />
<input name="something[]" />
<input name="something[]" />

Then you can access the fields using

然后您可以使用

document.getElementsByName('something[]')

So in the case above

所以在上述情况下

document.getElementsByName('something[]').length

will give you 3.

会给你3。

Then you add another fields, for example like:

然后添加另一个字段,例如:

var new_input = document.createElement('input');
new_input.type = 'text';
new_input.name = 'something[]';
document.body.appendChild(new_input);

Now if you try to count the fields with

现在,如果您尝试用

document.getElementsByName('something[]').length

you'll get 4 in Firefox as you would expect, but still 3 in IE.

如您所愿,您将在Firefox中获得4,但在IE中仍将获得3。

Bugs happen, c'est la vie 😀

发生错误,请稍候

Here's a demo

这是一个演示

Tested IE7 only, don't know if the bug exists in earlier versions.

仅测试了IE7,不知道该错误是否存在于早期版本中。

My example was with an HTML array using []s in field names, but the issue remains if you have regular names without brackets, for example you have radio buttons or checkboxes and you want to create more choices dynamically with JavaScript.

我的示例是使用在字段名称中使用[]HTML数组,但是如果您的常规名称不带方括号,例如您具有单选按钮或复选框,并且希望使用JavaScript动态创建更多选择,则问题仍然存在。

Tell your friends about this post on Facebook and Twitter

FacebookTwitter上告诉您的朋友有关此帖子的信息

翻译自: https://www.phpied.com/ie-has-a-problem-with-getelementsbyname/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值