简体   繁体   English

如何从包含的js文件中引用html元素

[英]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: 然后,site.js中保留了两个小功能来停用/激活我的按钮:

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. 我正在使用带有主页的Web表单。 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: 然后在master_include_head.html中包含如下所示的实际javascript函数:

<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? 我是否应该不能使用这种设计来引用单击按钮的ID,或者由于我包含文件的方式而丢失了对按钮的引用? 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: 为什么不使用jQuery附加点击事件,如下所示:

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

Side note. 边注。 I'm not sure there's any need for the return false; 我不确定是否需要返回false; statement in your onclick. 您的onclick中的声明。 Typically this would just contain the function name. 通常,它仅包含函数名称。 return false; 返回false; can be used in functions to prevent event bubbling, as you've set it I'm not sure it will have any effec 可以在函数中使用以防止事件冒泡,因为您已经设置了它,所以我不确定它是否会有效果

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

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