0

我有一个通过 ajax 提交到后端的表单,我正在用 javascript 编写一个通用的禁用函数,我可以用它来设置元素的 onclick。在浏览器中键入此内容,因此请忽略以下任何语法错误。

function(elementID , processingText) {
    var element = document.getElementById(elementID);
    if (element) {
        element.setAttribute("onClick", "alert('test')");
    }
}

所以基本上元素应该有一个 onclick 事件来设置警报。我可以确认 onclick 属性设置正确并且在 IE8+、Chrome 和 Firefox 中触发。它不会在 IE7 中触发。

我正在测试的元素是表单中的提交按钮(页面上的一个表单)。它有许多字段和一个提交按钮。

编辑代码通过一个动作调度,所以它应该提交,但直到警报被确认后/编辑

在过去的两个小时里,我一直在网上搜寻,但以下解决方案不起作用或不是一个选项 -

在表单中添加一个隐藏的输入字段。将提交按钮包装在标签中,并在此标签中设置 onclick。将 onclick 的大小写更改为 onClick

任何涉及在不使用 javascript 的情况下更改 html 的解决方案都不是一种选择,我正在尝试创建一个通用的 disableElement 函数。我可以将脚本定位在 IE7 上,因此它不必在所有浏览器中工作,只在 IE7 上工作。

任何帮助将不胜感激

4

2 回答 2

1

IE7 has a lot of compatibility issues, of which this is just one. If you're writing javascript that needs to be compatible with IE7, you will end up writing a lot of redundant code that does the same thing in two different ways to cater for different browsers you're supporting.

Issues like this in old browsers are precicely the reason why libraries like jQuery exist. jQuery does a lot of things, but one thing it does very well is iron out many of these nasty little quirks that crop up when writing cross-browser javascript.

The cross-browser issues have become less important in recent years, as modern browsers (including IE) have much better standards support, but if you're supporting old browsers , and old IE versions in particular, my recommendation is to use jQuery (or a similar library), because they have already solved this problem, and plenty of others that will catch you out.

If you do use jQuery, your code will become:

$(element).click(function() {alert('test');});

Before anyone points it out, yes I know the OP didn't specify jQuery in the question, and may not want a jQuery answer, but in this case I would say it is the best answer available, because if you don't use it, you will end up having to write much of the same compatibility code yourself that is already in jQuery.

于 2013-07-05T11:04:01.357 回答
1

IE 7 确实支持 setAttribute 方法,但似乎无法使用它更改 onclick 属性。有关此问题的更多信息,请查看:Why does an onclick property set with setAttribute failed to work in IE?

干杯

于 2013-07-05T10:50:53.853 回答