如何在不用css的情况下使用JQuery来检索和设置body属性

时间:2012-08-23 21:19:40

标签: jquery css

我这里有一些代码可以加载外部页面,当然也可以替换正文及其内容。哪个很好,除了body标签有一些属性我想要检索嵌入标签而不是.css。我无法更改页面,因为有数千页。任何建议都会有所帮助。

加载页面的代码:

$(document).ready(function() {
    $('[id=Page]').load($(JQCurrentPagelink).val(), function() {
});

样本正文标记:

<body background="/Image/ReviewFade02.jpg" leftmargin="20" topmargin="20" marginwidth="20" marginheight="20">

1 个答案:

答案 0 :(得分:0)

试试这个:

$.ajax({
    url: 'page-to-load.html',
    success: function(data) {
        // load the content of the other page into #ajax-div
        $('#ajax-div').html(data);
        // a RegEx pattern to grab the opening body tag
        var pattern=new RegExp("<body.*>");
        // grab the opening body tag
        var bodyOpeningTag = pattern.exec(data)[0];
        // remove everything we don't need ('<body ', '>' and quotes)
        var bodyAttributesString = bodyOpeningTag.replace('<body ', '');
        bodyAttributesString = bodyAttributesString.replace('>', '');
        bodyAttributesString = bodyAttributesString.replace(/\"/g,'');
        // split the string into a one dimensional array ('background=/images/about.jpg', 'leftmargin=20' etc)
        var bodyAttributesArray = bodyAttributesString.split(' ');
        // split each attribute item into a [attributename, value] array
        var bodyAttributesArray2d = new Array();
        for (var i = 0; i < bodyAttributesArray.length; i++) {
            bodyAttributesArray2d[i] = bodyAttributesArray[i].split('=');   
        }
    }
});

演示页面:

jQuery - ajax load another page and grab body attributes