模拟链接单击功能

时间:2013-06-03 19:05:07

标签: javascript

我正在网页上工作,我想模拟链接点击。

我设置它的方式是用户点击我们发送的eblast的链接,当页面加载时,视频将弹出所选链接。

这是网站,如果您点击图片或标题,它会弹出一个弹出框。我正在使用prettyPhoto。 http://dynamicdevsite.com/cmdnyc/audio-post-production-nyc.php

我有URL解析器设置,所以我的链接看起来像这个http://dynamicdevsite.com/cmdnyc/audio-post-production-nyc.php?ComedyCentral,url解析器看到ComedyCentral,然后触发我与该术语关联的函数,并且触发就好了。

链接点击模拟代码

function simulatedClick(target, options) {

        var event = target.ownerDocument.createEvent('MouseEvents'),
            options = options || {};

        //Set your default options to the right of ||
        var opts = {
            type: options.type                  || 'click',
            canBubble:options.canBubble             || true,
            cancelable:options.cancelable           || true,
            view:options.view                       || target.ownerDocument.defaultView, 
            detail:options.detail                   || 1,
            screenX:options.screenX                 || 0, //The coordinates within the entire page
            screenY:options.screenY                 || 0,
            clientX:options.clientX                 || 0, //The coordinates within the viewport
            clientY:options.clientY                 || 0,
            ctrlKey:options.ctrlKey                 || false,
            altKey:options.altKey                   || false,
            shiftKey:options.shiftKey               || false,
            metaKey:options.metaKey                 || false, //I *think* 'meta' is 'Cmd/Apple' on Mac, and 'Windows key' on Win. Not sure, though!
            button:options.button                   || 0, //0 = left, 1 = middle, 2 = right
            relatedTarget:options.relatedTarget     || null,
        }

        //Pass in the options
        event.initMouseEvent(
            opts.type,
            opts.canBubble,
            opts.cancelable,
            opts.view, 
            opts.detail,
            opts.screenX,
            opts.screenY,
            opts.clientX,
            opts.clientY,
            opts.ctrlKey,
            opts.altKey,
            opts.shiftKey,
            opts.metaKey,
            opts.button,
            opts.relatedTarget
        );

        //Fire the event
        target.dispatchEvent(event);
    }

function CC_Lightbox() {
      simulatedClick(document.getElementById("comedylink"));

}

错误
未捕获的TypeError:无法读取null的属性'ownerDocument'

注意:如果这个问题太局部化,我很抱歉,但此时我不知道是谁/在哪里提出问题。

1 个答案:

答案 0 :(得分:1)

我使用此代码来执行此操作

// change to this line
var evt = document.createEvent("MouseEvents");

evt.initMouseEvent('click',true,true,window,0,0,0,0,0,false,false,false,false,0,null);
element.dispatchEvent(evt);

第一行应该修复你的代码。

然后改变

var event = target.ownerDocument.createEvent('MouseEvents'),

var event = document.createEvent("MouseEvents"),

这应创建正确的事件并修复您的

Uncaught TypeError: Cannot read property 'ownerDocument' of null

错误。