选择 DOM 对象的 add() 和 appendChild() 是否相同? [英] Are add() and appendChild() the same for select DOM objects?

查看:16
本文介绍了选择 DOM 对象的 add() 和 appendChild() 是否相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个可更改选择下拉列表内容的小型 Web 应用程序.

I'm working on a small web application that changes the contents of a select drop-down.

我想知道 appendChild() 和 add() 是否都在 JavaScript 中对选定的 DOM 对象完成相同的任务?

I was wondering if appendChild() and add() both accomplish the same task on a select DOM object in JavaScript?


var someSelect = document.getElementById('select-list');
var newOption = document.createElement('option');
someSelect.appendChild(newOption);
// The above is the same as the following?
someSelect.add(newOption);

推荐答案

在这种情况下,我相信他们会完成相同的任务.

In this case, I believe they would accomplish the same task.

add( ) 专门通过 HTMLSelectElement 接口 专门用于向 select 元素添加选项,并有一些额外的选项(例如添加新元素的可选索引)option 等).

add( ) is provided specially via the HTMLSelectElement interface specifically to add options to a select element and has a few extra options (such as an optional index at which to add the new option, etc.).

appendChild( ) 会给你一个子节点的直接追加.

appendChild( ) will give you a straight append of the child node.

注意两种方法跨浏览器的不同实现:我认为这将是您最大的痛点.IIRC,IE 将子项附加到 select 时会导致问题,因此如果该方法存在,您可能希望 add 并回退到 appendChild.

Watch out for different implementations of both methods cross-browser: I think that would be your biggest pain point. IIRC, the IEs would cause problems when appending children to selects, so you might want to add if that method exists and fall back on appendChild.

这篇关于选择 DOM 对象的 add() 和 appendChild() 是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆