javascript 使用 node.js 访问 DOM

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34268804/
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-10-28 17:28:36  来源:igfitidea点击:

Access to DOM using node.js

javascriptnode.jsdomcheeriojsdom

提问by ameni

i want to access to html file and get an element by id using node.js, this is my html file :

我想访问 html 文件并使用 node.js 通过 id 获取一个元素,这是我的 html 文件:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Diagram </title>

<script>

    function generatePNG (oViewer) {
// some other code
            reader.onloadend = function() {
                base64data = reader.result;
                var image = document.createElement('img');
                image.setAttribute("id", "GraphImage");
                image.src = base64data;
                document.body.appendChild(image);
            }

        }, "image/png", oImageOptions);
        return sResult;

        var sResult = generatePNG (oEditor.viewer);

    });
</script>


</head>

<body >
    <div id="diagramContainer"></div>
</body>
</html>

I want to do get document.getElementById("GraphImage").srcbut with node.js. I've found that I can use cheerioor jsdomto acces the DOMwith node.js, so I've tried this code with cheerio:

我想做 document.getElementById("GraphImage").src但使用node.js。我发现我可以使用cheeriojsdom访问DOMnode.js,所以我尝试了以下代码cheerio

var cheerio = require('cheerio'),
    $ = cheerio.load('file.html');

But I didn't founnd the instruction that allow me to get the image.srcfrom the html file, like this instruction: document.getElementById("GraphImage").src

但是我没有找到允许我image.src从 html 文件中获取 的指令,如下所示:document.getElementById("GraphImage").src

回答by Alexandr Lazarev

cheerio.load()accepts a string as the argument. By setting: cheerio.load('file.html')cheerio will try to implement DOMfrom the string file.html. Obviously, that is not what you want.

cheerio.load()接受一个字符串作为参数。通过设置:cheerio.load('file.html')cheerio 将尝试DOM从字符串中实现file.html。显然,这不是你想要的。

You should get the htmldata from your file first, then pass it to the cheerio. Also as @Quentin metioned, cheerio is a cut down implementation of jQuery, so you should use jQuery selectors to get a ceratin element. For your particular case it would be: $("#GraphImage"). Here is how your code should look like:

您应该html首先从文件中获取数据,然后将其传递给cheerio. 同样正如@Quentin 所提到的,cheerio 是 jQuery 的简化实现,因此您应该使用 jQuery 选择器来获取 ceratin 元素。对于您的特定情况下,它是:$("#GraphImage")。您的代码应如下所示:

 var cheerio = require('cheerio'),
     $ = cheerio.load('file.html'),
     fs = require('fs');
 fs.readFile('./index.html', function (err, html) {
    if (err) {
        throw err; 
    } else {
        $ = cheerio.load(html.toString());
        console.log($('#GraphImage').attr('src'));   
    }

EDIT:

编辑:

Also, in the html file that you have provided, you are appending some objects to the DOM with the help of javascript. If you want to access them on the server, the javascript should be interpreted there. You can use something like phantomjsto achieve it, but things get much more complicated.

此外,在您提供的 html 文件中,您在 javascript 的帮助下将一些对象附加到 DOM。如果你想在服务器上访问它们,javascript 应该在那里被解释。你可以使用类似的东西phantomjs来实现它,但事情变得更加复杂。

回答by silverfighter

It looks like your mixing client side and server side javascript.

看起来您混合了客户端和服务器端 javascript。

but to answer your question you can access the src in the following way:

但要回答您的问题,您可以通过以下方式访问 src:

 var src = $('#GraphImage').attr("src");

make sure you first load your html file with fs

确保您首先加载您的 html 文件 fs

// EDIT:Your are getting 'undefined' because the img tag is dynamically generated and not present at the moment you are loading the file with node on the server. That's what I meant your are mixing client code with server side code. You might want to grab the diagramContainer $('#diagramContainer')and add an image tag inside it and set the source. $('#diagramContainer').prepend('<img id="theImg" src="theImg.png" />')

//编辑:您得到“未定义”,因为 img 标记是动态生成的,并且在您使用服务器上的节点加载文件时不存在。这就是我的意思是您将客户端代码与服务器端代码混合在一起。您可能想要获取 diagramContainer$('#diagramContainer')并在其中添加一个图像标记并设置源。$('#diagramContainer').prepend('<img id="theImg" src="theImg.png" />')

If you have a path you can set it directly if you generate the png on the server an have a binary stream things can get more tricky.

如果你有一个路径,你可以直接设置它,如果你在服务器上生成 png 并且有一个二进制流,事情会变得更加棘手。