createElement - 选择散布在文本中间的框

时间:2012-06-22 12:07:13

标签: javascript html createelement

这是我正在尝试创建的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);

顺便说一句:我也承认,我必须创建select选项。

感谢。

3 个答案:

答案 0 :(得分:4)

还有一个名为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 );

在这里,您可以找到一个示例小提琴:link

答案 1 :(得分:1)

我认为你需要这个:

<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

答案 2 :(得分:1)

这个怎么样?我改编了mdn createElement的例子。 Fiddle

<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()​