JQuery附加了stange行为 [英] JQuery append stange behavior

查看:102
本文介绍了JQuery附加了stange行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法解释这个 .append()行为......

I can't explain this .append() behavior...

var listTopic = $.parseJSON(data);
for(i = 0; i < listTopic.length ; i++)
{
     $('#idSelect').append('<option>').append(listTopic[i].name).append('</option>');
}

输出:

<option></option>
value1
<option></option>
value2


推荐答案

看起来浏览器是因插入的部分标签而自动插入关闭/打开标签。

It looks like the browser is automatically inserting closing/opening tags because of the partial tags you are inserting.

您可以使用以下代码:

var listTopic = $.parseJSON(data);
for(i = 0; i < listTopic.length ; i++) {
  $('#idSelect').append('<option>' + listTopic[i].name + '</option>');
}

或者,你也可以使用:

var listTopic = $.parseJSON(data);
for(i = 0; i < listTopic.length ; i++) {
  $('#idSelect').append($('<option />').text(listTopic[i].name));
}

如果你想设置 / text同时:

And if you want to set the value/text at the same time:

var listTopic = $.parseJSON(data);
for(i = 0; i < listTopic.length ; i++) {
  $('#idSelect').append($('<option />').val(listTopic[i].name).text(listTopic[i].name));
}

这篇关于JQuery附加了stange行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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