使用$()构造函数在JQuery中创建嵌套元素

时间:2022-03-02 19:17:44

I can't get JQuery's $() element constructor to work right. The following works right (using expect.js for the expect() calls):

我无法让JQuery的$()元素构造函数正常工作。以下工作正常(使用expect.js进行expect()调用):

var p = $('<div id="1"><div id="2">middle div</div></div>');
expect(p.children('div')).not.to.be(undefined); //passes
expect(p.children('div').attr('id')).to.equal('2'); //passes

But the following doesn't work

但以下不起作用

var p = $('<p id="1"><div id="2">middle div</div></p>');
expect(p.children('div')).not.to.be(undefined); //passes
expect(p.children('div').attr('id')).to.equal('2'); //fails

Any tips on how to get this to work right?

有关如何使其正常工作的任何提示?

3 个解决方案

#1


3  

The HTML markup is wrong. You cannot put a block-level element like <div> into a <p> element. That's why the HTML is actually (I think this depends on the browser) most likely parsed as:

HTML标记是错误的。您不能将

之类的块级元素放入

元素中。这就是为什么HTML实际上(我认为这取决于浏览器)最有可能被解析为:

<p id="1"></p><div id="2">middle div</div>

or (in chrome):

或(铬):

<p id="1"></p><div id="2">middle div</div><p></p>

You can verify this easily via console.log(p);

您可以通过console.log(p)轻松验证这一点;

#2


1  

The <div> is being ejected because it's not valid to have a <div> inside a <p>.

被弹出,因为在

中有

无效。

#3


1  

You should try this:

你应该试试这个:

expect($('#1').find('div').attr('id').to.equal('2');

Edit: Niko and The System are right.. a div cannot be in a p though.

编辑:Niko和系统是正确的..但div不能在p中。

#1


3  

The HTML markup is wrong. You cannot put a block-level element like <div> into a <p> element. That's why the HTML is actually (I think this depends on the browser) most likely parsed as:

HTML标记是错误的。您不能将

之类的块级元素放入

元素中。这就是为什么HTML实际上(我认为这取决于浏览器)最有可能被解析为:

<p id="1"></p><div id="2">middle div</div>

or (in chrome):

或(铬):

<p id="1"></p><div id="2">middle div</div><p></p>

You can verify this easily via console.log(p);

您可以通过console.log(p)轻松验证这一点;

#2


1  

The <div> is being ejected because it's not valid to have a <div> inside a <p>.

被弹出,因为在

中有

无效。

#3


1  

You should try this:

你应该试试这个:

expect($('#1').find('div').attr('id').to.equal('2');

Edit: Niko and The System are right.. a div cannot be in a p though.

编辑:Niko和系统是正确的..但div不能在p中。