简体   繁体   English

按钮单击在JavaScript中不起作用

[英]Button click not working in javascript

I'm trying to do a click in a html button through javascript , but I can't make it work. 我正在尝试通过javascript单击html按钮,但无法正常工作。

This is the button I'm trying to click with javascript (it works when I click it) 这是我尝试使用javascript单击的按钮(单击该按钮即可使用)

<button id="btnClean" runat="server" type="button" class="btn btn-warning btn-cons m-b-10" onserverclick="btnClean_Click">
    <i class="fa fa-trash-o"></i>
    <span class="bold m-l-3">Limpar</span>
 </button>

This is the button that calls the javascript function: 这是调用javascript函数的按钮:

<button id="btnCreateOS" type="button" class="btn btn-success btn-cons m-b-10" onclick="Clean();">
    <i class="fa fa-save"></i>
    <span class="bold m-l-3">Criar</span>
</button>

And this is my javascript (it is located under <form> tag in my .aspx page): 这是我的javascript (位于.aspx页面中的<form>标记下):

<script type="text/javascript">        

    function Clean() {

        document.getElementById("btnClean").click();

    }

</script>

And finally, this is the asp method: 最后,这是asp方法:

public void btnClean_Click(object sender, EventArgs e)
{
   CleanFields();
}

Any ideas what I'm doing wrong? 有什么想法我做错了吗?

Bsically what happens, when you are using master and content page then it always changes its id according to it default behavior. 基本上会发生什么,当您使用母版页和内容页时,它将始终根据其默认行为更改其ID。

function Clean() {
        //document.getElementById("btnClean").click()

        document.getElementById('<%= btnClean.ClientID %>').click();
    }

Another solution you just add ClientIdMode="Static" . 您只需添加ClientIdMode =“ Static”的另一种解决方案。

<button id="btnClean" runat="server" clientidmode="Static" type="button" class="btn btn-warning btn-cons m-b-10" onserverclick="btnClean_Click">
        <i class="fa fa-trash-o"></i>
        <span class="bold m-l-3">Limpar</span>
    </button>

in your button.. 在您的按钮..

Then your current javascript code will also work.. 然后,您当前的javascript代码也将起作用。

function Clean() {
        document.getElementById("btnClean").click();

        //document.getElementById('<%= btnClean.ClientID %>').click();
    }

You should use 你应该用

document.getElementById("btnClean").trigger("click");

instead, because it's faster. 相反,因为它更快。 Maybe you should also try to prevent default behaviour in btnClear_Click? 也许您还应该尝试防止btnClear_Click中的默认行为? Try to add a console.log("a") (or rather "b" at the second) to your two functions, to see, if and which of the two functions are running. 尝试在两个函数中添加console.log(“ a”)(或者第二个为“ b”),以查看两个函数是否正在运行以及哪个正在运行。

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

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