简体   繁体   中英

How to reference html element from included js-file

I created this test case which works as expected:

<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="site.js"></script>

<script>
function click_me() {
    deActivateButton("Please wait ..", "#btnX");
    activateButton("Click me 2", "#btnX");
}
</script>

<button type="button" id="btnX" onclick="click_me(); return false;">Click me
</button>

And then two small functions kept in site.js to deactivate/activate my buttons:

function deActivateButton(btnText, id) {
    $(id).text(btnText);
    $(id).prop("disabled", true);
}

function activateButton(btnText, id) {
    $(id).text(btnText);
    $(id).prop("disabled", false);
}

This works fine, but fails when I use the code in my application. I'm using web forms with a master page. The master page loads include file:

<%Response.WriteFile("Content/Files/master_include_head.html");%>

And then in master_include_head.html I include the actual javascript functions like this:

<script src="site.js"></script>

What can I be doing wrong here? There are no error messages, it just dies. Shouldn't I be able to reference the id of the clicked button with this design, or is the reference to the button lost because of the way I include files? Can it be a cache problem?

Are you not just setting and then clearing then immediately clearing the value in your code?

So you are activating then immediately de-activating your button?

Just a little note. Why not use jQuery to attach your click events as follows:

$("#btnX").click(function(e) {
     // Do stuff
});

Side note. I'm not sure there's any need for the return false; statement in your onclick. Typically this would just contain the function name. return false; can be used in functions to prevent event bubbling, as you've set it I'm not sure it will have any effec

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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