在不单击按钮的情况下运行按钮中的代码

Run code inside a button without clicking it

本文关键字:按钮 代码 运行 情况下 单击      更新时间:2023-09-26

下面的代码来自一个弹出式警报窗口,在关于如何使用的示例页面中有一个按钮说"错误",当你点击它时窗口出现。

<button class="btn btn-danger notification" data-verti-pos="bottom" data-horiz- pos="right" data-message="<i class='fa fa-frown-o' style='padding-right:6px'></i> Oops... Something went wrong. Hope we don''t see me again." data-type="error" type="button"></button>

问题是,我想调用窗口而不需要点击按钮,我试图调用它在这个如果有条件。

if(codigo=="matricula_longitud"){
        //I know the part of code below is totally wrong
        document.getElementById("errores").innerHTML='<div class="alert alert-warning fade in"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><strong>Warning!</strong> Better check yourself, youre not looking too good.</div>';
    return "si";
}

我是新的编程,所以任何建议将不胜感激。谢谢你。

您可以将内容包装在一个函数中,该函数从按钮和其他函数的事件处理程序中调用,其中显示窗口而不需要单击按钮。

var showWindow = function() {
    alert("La matricula es muy corta")
    //I know the part of code below is totally wrong
    document.getElementById("errores").innerHTML='...';
    return "si";
};

然后在你的按钮处理程序

if(codigo=="matricula_longitud"){ 
    return showWindow();
}

在你的另一个函数中,如果你想向用户显示它,只需调用showWindow()

如果你想检查一个条件,最好使用严格的相等性检查,===!==而不是==!=。请参考这个问题作进一步的解释。

至少,你可以使用jquery

<button id="myBtn" class="btn btn-danger notification" data-verti-pos="bottom" data-horiz- pos="right" data-message="<i class='fa fa-frown-o' style='padding-right:6px'></i> Oops... Something went wrong. Hope we don''t see me again." data-type="error" type="button"></button>
$('#myBtn').click();