createElement-选择穿插在文本中间的框

createElement - select boxes interspersed in the midst of text

本文关键字:中间 文本 选择 createElement-      更新时间:2023-09-26

这是我试图创建的HTML:

<td>
Tiana is
<select name="U4">...</select>
keen to go to the
<select name="J4">...</select>
market.
</td>

正如你所看到的,有一个<td>元素,它包含一个散文句子,中间有选择框

使用$('#id').html(...);很容易。我想做的是使用createElement构建它。如何在其他文本的中间创建选择框?以下代码是一个开始:(

var doc = document,
    fr = doc.createDocumentFragment(),
    td = doc.createElement("td"),
    sel1 = doc.createElement("select"),
    sel2 = doc.createElement("select");
td.innerHTML = "Tiana is keen to go to the market";
sel1.name = "U4";
sel2.name = "J4";  
fr.appendChild(td);
td.appendChild(sel1);    // But these are not in the middle of the sentence
td.appendChild(sel2);

BTW:我也认识到,我必须创建select选项。

谢谢。

还有一个名为createTextNode()(MDN-docu(的函数,用于将简单文本创建为内容。因此,一种解决方案是相应地拆分文本,将其转换为文本节点,然后也附加它:

var doc = document,
    fr = doc.createDocumentFragment(),
    td = doc.createElement("td"),
    sel1 = doc.createElement("select"),
    sel2 = doc.createElement("select"),
    text1 = doc.createTextNode( 'Tiana is ' ),
    text2 = doc.createTextNode( ' keen to go to the ' ),
    text3 = doc.createTextNode(  'market' );
sel1.name = "U4";
sel2.name = "J4";  
fr.appendChild(td);
td.appendChild( text1 );
td.appendChild(sel1); 
td.appendChild( text2 );
td.appendChild(sel2);
td.appendChild( text3 );

在这里你可以找到一个小提琴的例子:链接。

我想你需要这个:

<td>
<span>Tiana is</span>
<select name="U4">...</select>
<span>keen to go to the</span>
<select name="J4">...</select>
<span>market.</span>
</td>

或者这样做:

td.innerHTML = 'Tiana is <select id="U4" name="U4" /> keen to go to the <select id="J4" name="J4" /> market';
var uOpt1 = document.createElement('option');
//Set option properties
td.getElementById('U4').appendChild(uOpt1); //etc

这个怎么样?我改编了mdn-createElement中的示例。不停摆弄

<div id='org_div1'> The text above has been created dynamically.</div>​

var my_div = null;
var newDiv = null;
var newSelect = null;
var newDiv2 = null;
function addElement()
{
  // create a new div element
  // and give it some content
  newDiv = document.createElement("div");
  newContent = document.createTextNode("Hi there and greetings!");
  newSelect = document.createElement("select");
  newSelect.innerHTML='<option value="value1">Value 1</option><option value="value2" selected>Value 2</option><option value="value3">Value 3</option>';
  newDiv.appendChild(newContent); //add the text node to the newly created div.
  newDiv.appendChild(newSelect)
   newDiv2 = document.createElement("span");
  newDiv2.appendChild(document.createTextNode("Foo"));
  newDiv.appendChild(newDiv2)
  // add the newly created element and it's content into the DOM
  my_div = document.getElementById("org_div1");
  document.body.insertBefore(newDiv, my_div);
}
addElement()​