在JavaScript OnClick中模拟点击事件会导致错误

时间:2017-07-07 04:53:21

标签: javascript jquery

我正在使用<li>标记构建一个包含一些选项的上下文菜单,如下所示。我需要在另一个ID(图像)上模拟点击事件,当我选择并从上下文菜单中单击此选项时..我只能在onclick中执行瞬时执行功能,如下面的代码所示 -

编辑代码以提高清晰度

var functionMain = function ContextMenu$functionMain(items, targetId) {
    $(menu).html(buildItems(items, targetId));
};

var buildItems = function ContextMenu$buildItems(items, targetId) {
    var i, result;
    result = '';
    for (i = 0; i < items.length; ++i) {
        var reportId = targetId.substring(targetId.indexOf(':') + 1);
        var reportIdFormed = $('#' + reportId + 'run' + runReportLinkName);
        result += '<li><a href="javascript:void(0);" style="text-decoration:none" onclick="(function(){'+ reportIdFormed+'.trigger(\'click\'); })();"> Run HTML </a></li>';
    }
    return result;
};

以上代码导致未捕获的SyntaxError:意外的标识符

结果HTML - &gt; <a href="javascript:void(0);" style="text-decoration:none" onclick="(function(){[object Object].trigger('click'); })();">Run HTML</a>

如何摆脱这个问题?

3 个答案:

答案 0 :(得分:2)

使用委派活动

var reportId = targetId.substring(targetId.indexOf(':') + 1); 
var reportIdFormed = $('#' + reportId + 'run' + runReportLinkName);

result += '<li><a href="javascript:void(0);" style="text-decoration:none" class="delegated-event"> Run HTML </a></li>';//add a class 

$('body').on('click','.delegated-event',function(){ //delegate the event based on that class
   reportIdFormed.trigger('click');
})

如果选择器为每个元素更改,那么您需要一个属性来存储选择器:

var reportIdFormed = '#' + reportId + 'run' + runReportLinkName;//make it a string

    result += '<li><a href="javascript:void(0);" style="text-decoration:none" class="delegated-event" data-selector="'+reportIdFormed+'"> Run HTML </a></li>';//add a class 

$('body').on('click','.delegated-event',function(){ //delegate the event based on that class
       reportIdFormed = $($(this).attr('data-selector'));//get the selector
       reportIdFormed.trigger('click');
    })

答案 1 :(得分:1)

你的代码的问题在于你试图传递和对象引用而不是ID字符串,所以你打印那个,所以JS不能打印和JS对象,所以它会打印引用[object Object]所以你应该这样做:

var reportId = targetId.substring(targetId.indexOf(':') + 1); //e.g. rpt1234
var reportIdFormed = '#' + reportId + 'run' + runReportLinkName; //e.g. rpt1234runHTML
result += '<li><a href="javascript:void(0);" style="text-decoration:none" onclick="handleTrigger(reportIdFormed)"> Run HTML </a></li>';

您的代码JS

function handleTrigger(id) {
 var target = $(id);
 if (target.length) {
   target.trigger("click")
 }
}

答案 2 :(得分:1)

试试这个

var reportId = targetId.substring(targetId.indexOf(':') + 1); //e.g. rpt1234
var reportIdFormed = reportId + 'run' + runReportLinkName; //e.g. rpt1234runHTML
result += '<li><a href="javascript:void(0);" style="text-decoration:none" onclick="(function(){document.getElementById(\''+ reportIdFormed+'\').trigger(\'click\'); })();"> Run HTML </a></li>';