jQuery 获取 div 内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5487309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:15:01  来源:igfitidea点击:

jQuery get div content

jqueryfind

提问by OHLáLá

I have the following div structure, but this structure is changing

我有以下 div 结构,但这个结构正在改变

<div class="rt-container">
    <div class="rt-block">
        <div id="rt-mainbody">
            <div id="responseMessage">Welcome bogyoro. Now you are loged in.</div>
            <div id="responseErrorMessage">5</div>
        </div>
    </div>
</div>

I'm using the following code to get the responseMessage content:

我正在使用以下代码来获取 responseMessage 内容:

var div = logReg.query("<div>").html(msg);
var message = div.children('#responseMessage').html();
var isValid = div.children('#responseErrorMessage').html();
if(isValid == null)
{
    message = div.find('#responseMessage').html();
    isValid = div.find('#responseErrorMessage').html();
}

But the isValid is null.

但 isValid 为空。

Update:

更新:

var logReg = {};
logReg.query = jQuery.noConflict(true);

回答by rahul

If you want to get the html of an element having an id, then you can simply use the id selector.

如果您想获取具有 id 的元素的 html,那么您可以简单地使用 id 选择器。

$("#responseMessage").html(); 

回答by cllpse

var isValid = div.children('#responseErrorMessage').html();

if (isValid == null) { }

Will always result in false. If the element exists, that is.

总是会导致false。如果元素存在,那就是。

If an element is empty, the return will be an empty string. Try out if (isValid == "") { }instead.

如果元素为空,则返回一个空字符串。试试吧if (isValid == "") { }

回答by Mike Thomsen

Why not just do this?

为什么不这样做呢?

var message = logReg.query('#responseMessage').html();  
var isValid = logReg.query('#responseErrorMessage').html();

The top line of your code is problematic. It'll return an entire array of div tags. So when you do div.children('...') you're doing that for the entire list of divs.

代码的第一行有问题。它将返回整个 div 标签数组。因此,当您执行 div.children('...') 时,您正在为整个 div 列表执行此操作。

Since you have the anchors for the specific elements, just look them up directly.

由于您拥有特定元素的锚点,只需直接查找即可。