使用jQuery包含文件并获取它's的内容长度

Including file with jQuery and getting it's content length

本文关键字:包含 jQuery 文件 获取 使用      更新时间:2023-09-26

用jQuery:做这样的事情可能吗

我有几乎空的html文件index.php(没有内容,只有重要的标签),还有文件content.php,里面有所有的网页内容,例如:blablabla,很多标签,div和其他内容。例如,所有这些内容都是700px长。

现在我想用jQuery做的事情是:在文件index.php中,在标记之间输入这个命令,然后再添加一个jQuery,将.content.height()放入任何变量中(这样它就会显示文件content.php中的所有内容有多长(在本例中为700px))。

我尝试过做这些事情,一切都很顺利,直到我必须将文件的内容长度放入变量的地方。

这是我的密码。也许有人可以修复它,但在我看来,这都是错误的。

所有jQuery命令都是在index.php文件中编写的。

$(document).ready(function() {
    $('body').append("<?php include ('content.php'); ?>");
    $length = $('.content').length;
});

$length显示0,但应该大于0^_^

最重要的是在jQuery或任何其他语言的帮助下,从index.php文件中了解content.php文件中内容的长度。使用.load('content.php')命令也可以包含文件,但该命令看不到包含文件的内容长度。

谢谢你的帮助!:)

$('body').append("<?php include ('content.php'); ?>");

不要那样做没有充分的理由这么做,而且很可能你会遇到换行符和/或无标题引号的问题。只需在正文末尾直接添加<?php include ('content.php'); ?>,然后从document.ready中获取高度(您几乎达到了):

$(document).ready(function() {
    var height = $('.content').height();
    alert(height) // or do something with it
});

你在问题中提到了.load('content.php')。如果我建议的直接php包含不适合您的需求,请执行以下操作:

$(document).ready(function() {
    // You probably want a more specific container instead of body
    $(body).load('content.php', function(){
        // You can only read the height inside this callback
        var height = $('.content').height();
        alert(height) // or do something with it
        // Continue your program flow from here
        // (for example, call a function)
    }); 
    // CAUTION: here the content probably didn't load yet.
    // If you need to refer to it, do it from the callback above.
});

最后:如果您真的为$('.content').length获得了0,那是因为在您调用它的时候,DOM中没有类为"content"的元素。jQuery对象的length属性告诉有多少元素与您使用的选择器匹配,因此零为零。

谢谢。问题是我必须提醒进入(身体)的高度。加载代码,不要放在那个代码旁边。

正确:

$(document).ready(function() {
    $('body').load('content.php', function(){
        alert($('.content').height());
    });
});

错误:

$(document).ready(function() {
    $('body').load(content.php', function(){})
    alert($('.content').height());
});

据我所知,您想要内容的实际高度(以像素为单位)吗?在这种情况下,听从Malcolm的建议,使用.height()而不是.length.

$(document).ready(function() {
    $('body').append("<?php include ('content.php'); ?>");
    $length = $('.content').length;
});

相反,如果你想看看块中有多少字符,你可以这样做。

$(document).ready(function() {
    $('body').append("<?php include ('content.php'); ?>");
    $length = $('.content').html().length;
});