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

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

问题描述

我正在研究一个改变选择下拉菜单内容的小型Web应用程序。



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

  
var someSelect = document.getElementById (选择列表);
var newOption = document.createElement('option');
someSelect.appendChild(newOption);
//以上与以下相同?
someSelect.add(newOption);


解决方案

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



add()是通过 HTMLSelectElement 界面专门为选择元素,并有一些额外的选项(例如添加新的选项的可选索引等)。



appendChild()将给你一个直接附加的子节点。



注意两种方法跨浏览器的不同实现:我认为这将是您最大的痛点。 IIRC,当将孩子附加到选择 s时,IE会导致问题,因此如果该方法存在,您可能需要添加并退回 appendChild


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

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( ) 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( ) will give you a straight append of the child node.

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天全站免登陆