创建元素三种方法

1、动态创建元素一 document.write()
例如向页面中输出一个 li 标签


body标签中就会插入但是这种方法几乎不用,因为这回影响页面的布局,甚至会将页面原来的内容冲刷掉,从而只显示输出内容
2、动态创建元素二 innerHTML

div标签中就会插入一个p标签,并在在页面上输出“这是标签”,当需要添加的标签比较多的时候使用这种方式。
3、动态创建元素三 document.createElement()

div标签下面就会创建了一个li标签,当需要动态创建的标签比较少的时候就使用这种方式

在uniapp中,动态创建元素有多种方法,具体如下: 1. **使用`v-for`指令**: `v-for`指令是Vue.js中用于遍历数组或对象的指令,可以在模板中动态生成元素。 ```html <template> <view v-for="(item, index) in items" :key="index"> {{ item }} </view> </template> <script> export default { data() { return { items: ['Item 1', 'Item 2', 'Item 3'] } } } </script> ``` 2. **使用`$createElement`方法**: 通过`render`函数和`$createElement`方法可以在JavaScript中动态创建元素。 ```html <template> <div> <child-component></child-component> </div> </template> <script> export default { mounted() { const h = this.$createElement; const child = h('p', 'Hello, dynamic element!'); this.$children[0].$el.appendChild(child); } } </script> ``` 3. **使用`document.createElement`方法**: 在uniapp中,可以通过`document.createElement`方法在原生JavaScript中创建元素,然后将其添加到页面中。 ```html <template> <view id="container"></view> </template> <script> export default { mounted() { const container = document.getElementById('container'); const newElement = document.createElement('view'); newElement.textContent = 'Hello, dynamic element!'; container.appendChild(newElement); } } </script> ``` 4. **使用`uni.createSelectorQuery`方法**: `uni.createSelectorQuery`方法可以用于获取元素的引用,然后通过`append`方法动态添加元素。 ```html <template> <view id="container"></view> </template> <script> export default { mounted() { const query = uni.createSelectorQuery().in(this); query.select('#container').boundingClientRect((rect) => { const newElement = document.createElement('view'); newElement.textContent = 'Hello, dynamic element!'; document.getElementById('container').appendChild(newElement); }).exec(); } } </script> ``` 这些方法各有优缺点,具体使用哪种方法取决于实际需求和场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值