Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 是否有一个等效的elem.innerHTML来获取标记体中的代码?_Javascript_Html_Dom - Fatal编程技术网

Javascript 是否有一个等效的elem.innerHTML来获取标记体中的代码?

Javascript 是否有一个等效的elem.innerHTML来获取标记体中的代码?,javascript,html,dom,Javascript,Html,Dom,如果我有以下资料: <p class="demo" id="first_p"> This is the first paragraph in the page and it says stuff in it. </p> 得到 This is the first paragraph in the page and it says stuff in it. 但是,是否有一些简单的东西可以作为字符串返回 class="demo" id="first_p" 我知道

如果我有以下资料:

<p class="demo" id="first_p">
    This is the first paragraph in the page and it says stuff in it.
</p>
得到

This is the first paragraph in the page and it says stuff in it. 
但是,是否有一些简单的东西可以作为字符串返回

class="demo" id="first_p"

我知道我可以遍历元素的所有属性来分别获取每个属性,但是有没有返回
tagHTML
之类的函数?

您可以使用
document.getElementById(“first_p”).attributes
来获取该DOM元素上所有属性的数组


如果希望将它们全部放在一个字符串中,只需执行以下操作:
document.getElementById(“first_p”).attributes.join(“”)
要获得所需的输出,可以尝试以下操作:-

      var attributes = '';
            for(var i=0; i<document.getElementById("first_p").attributes.length; i++){
                var attr = document.getElementById("first_p").attributes[i];
                attributes += attr.nodeName+"='"+attr.nodeValue+"' "
            }
            console.log(attributes);
var属性=”;

对于(var i=0;i它不是一个内置属性,但是您可以使用类似数组的对象
属性
来获取您要查找的内容

Array.prototype.map.call(element.attributes, function (el) {
  return el.name + '="' + el.value + '"';
}).join(' ')
这是假设浏览器支持该功能。
Array.prototype.map.call
部分是因为
attributes
不是一个真正的数组,没有
join
方法,但因为它是一个类似JavaScript的数组,它的动态性允许我们调用
map

当前页面页脚为div的示例:

var element = document.getElementById('footer')
Array.prototype.map.call(element.attributes, function (el) {
  return el.name + '="' + el.value + '"';
}).join(' ');
// "id="footer" class="categories""

好的,虽然目前还没有直接做到这一点的方法(尽管使用
节点
属性的方法是一种更可靠的方法,但一种选择是自己创建此方法:

HTMLElement.prototype.tagHTML = function(){
    // we create a clone to avoid doing anything to the original:
    var clone = this.cloneNode(),
    // creating a regex, using new RegExp, in order to create it
    // dynamically, and inserting the node's tagName:
        re = new RegExp('<' + this.tagName + '\\s+','i'),
    // 'empty' variables for later:
        closure, str;

    // removing all the child-nodes of the clone (we only want the
    // contents of the Node's opening HTML tag, so remove everything else):
    while (clone.firstChild){
        clone.removeChild(clone.firstChild);
    }

    // we get the outerHTML of the Node as a string,
    // remove the opening '<' and the tagName and a following space,
    // using the above regular expression:
    str = clone.outerHTML.replace(re,'');

    // naively determining whether the element is void
    // (ends with '/>') or not (ends with '>'):
    closure = str.indexOf('/>') > -1 ? '/>' : '>';

    // we get the string of HTML from the beginning until the closing
    // string we assumed just now, and then trim any leading/trailing
    // white-space using trim(). And, of course, we return that string:
    return str.substring(0,str.indexOf(closure)).trim();
};

console.log(document.getElementById('test').tagHTML());
console.log(document.getElementById('demo').tagHTML());
HTMLElement.prototype.tagHTML=function(){
//我们创建克隆以避免对原始文件做任何操作:
var clone=this.cloneNode(),
//使用新的RegExp创建一个regex,以便创建它
//动态,并插入节点的标记名:
re=新的RegExp('-1?'/>':'>';
//我们从开始到结束都会得到HTML字符串
//我们刚才假设的字符串,然后修剪任何前导/尾随
//使用trim()返回空白。当然,我们返回该字符串:
返回str.substring(0,str.indexOf(closure)).trim();
};
log(document.getElementById('test').tagHTML());
log(document.getElementById('demo').tagHTML());

.

下面的代码有点令人费解:我把它写成一行,但我在这里把它分成了几行。但是这将得到一个简单的对象,其中键是属性名,值是相应属性的值。

Array.prototype.reduce.call(
    document.getElementById('first_p').attributes,
    function (attributes, currentAttribute) {
        attributes[currentAttribute.name] = currentAttribute.value;
        return attributes;
    },
    {}
);
通过此过程,
document.getElementById('first_p').attributes
获取元素属性的NamedNodeMap。NamedNodeMap不是数组,而是
Array.prototype.reduce.call(…)
调用
Array.prototype.reduce
在NamedNodeMap上,就像它是一个数组一样。我们可以这样做,因为NamedNodeMap是编写的,所以可以像数组一样访问它

但我们不能到此为止。我提到的NamedNodeMap是一个Attr对象数组,而不是一个名值对对象。我们需要将其转换,这就是使用
array.prototype.reduce
的其他参数的地方

当它不是以一种奇怪的方式被调用时,
Array.prototype.reduce
接受两个参数。第二个参数(因为我们调用它的方式而对我们来说是第三个参数)是我们想要构建的对象。在我们的例子中,这是一个全新的裸对象:最后看到的
{}

Array.prototype.reduce的第一个参数(这也是我们的第二个参数)是另一个函数。该函数将为循环中的每个项调用一次,但它需要两个参数。第二个参数是当前循环项,这很容易理解,但第一个参数有点疯狂。我们第一次调用该函数时,它的第一个参数是我们要构建的对象(即,
Array.prototype.reduce
的最后一个参数。每次之后,第一个参数都是该函数上次调用时返回的值。
Array.prototype.reduce
返回其内部函数上次调用时返回的值

因此,我们从一个空对象开始。然后对于元素属性中的每个属性,我们向该对象添加一些内容,并返回它。当最后一次调用完成时,该对象完成,因此我们返回它。这就是我们制作属性列表的方式

如果您希望在标记中使用精确的代码,如字符串,那么恐怕没有标准函数可以精确地获得该代码。但是我们可以通过类似的设置获得该代码的近似值。

Array.prototype.map.call(
    document.getElementById('first_p').attributes,
    function (currentAttribute) {
        return currentAttribute.name + '=' + JSON.stringify(currentAttribute.value);
    }
).join(' ');

基本原理是一样的:我们使用NamedNodeMap并在其上调用数组函数,但这次我们使用
map
而不是
reduce
。您可以将
map
视为
reduce
的一个特例:它总是构建一个数组,原始数组中的每个元素都有一个元素。因为这样,您甚至不需要提及正在构建的对象:回调函数只有一个参数,我们只需返回要放入新数组中的内容。完成后,我们就有了一个“name=”value的数组'字符串,然后我们用''连接它。

没有AFAIK,但为什么需要这样做?实际使用情况是什么?document.getElementById(“first_p”).outerHTML.split(/[]/)[1]在没有无效属性的情况下应该这样做。@elclars我正在尝试将HTML转换为JavaScript数组,我可以将其发送到PHP页面,该页面保存该数组,然后加载该数组来重建HTML。我知道这没有什么意义,但我正在尝试将HTML转换为PHP可操作的数据结构。这是我不想看到的原因只保存原始HTML。因为我可以在一个标记上使用
.innerHTML
来获得可保存的内容,但这不是我真正的意图。
.attributes
不是数组;它是类型,所以我认为它实际上没有
连接Array.prototype.map.call(
    document.getElementById('first_p').attributes,
    function (currentAttribute) {
        return currentAttribute.name + '=' + JSON.stringify(currentAttribute.value);
    }
).join(' ');