简体   繁体   English

为什么addEventListener在Node.js的jsdom模块中不起作用

[英]Why addEventListener doesn't work in jsdom module for nodejs

I use the following code to call some stuff after clicking by an element on a page 单击页面上的某个元素后,我使用以下代码来调用某些内容

var http = require('http');
var fs = require('fs');
var jsdom = require('jsdom');

http.createServer(function(req, res) {

    res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});
    var document = new jsdom.JSDOM('<!doctype html><html><head></head><body><p>Text</p></body></html>').window.document;
    document.getElementsByTagName('p')[0].addEventListener('click', function() {
        alert('OK');
    });     
    var page = '<!doctype html><html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>';
    res.end(page);

}).listen(80, 'localhost');

But if I click the paragraph, nothing happens 但是,如果我单击该段落,则什么也不会发生

I read the answer by the link https://stackoverflow.com/a/36804251/10587062 but I didn't understand how to resolve my problem 我通过链接https://stackoverflow.com/a/36804251/10587062阅读了答案,但我不明白如何解决我的问题

You're hooking the click handler on the server , but you're clicking the element on the client . 您将钩子click处理程序挂接到服务器上 ,但要单击客户端上的元素。

Instead, you need to send script code to the client that hooks up the event handler on the DOM element the browser renders, to handle the click and show the alert (which is also a client-side thing). 相反,您需要将脚本代码发送到客户端,该脚本代码将事件处理程序与浏览器呈现的DOM元素挂钩,以处理单击并显示警报(这也是客户端的事情)。 (Which means you don't need JSDom; that's for doing DOM manipulation — like web scraping — server-side.) (这意味着您不需要JSm;这是在服务器端进行DOM操作(如Web抓取)。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM