您好,我对现有的 javascript 代码有疑问。
背景是一些JSP标签自动包含JS函数,然后一些html元素需要运行这个函数。 但重点是,有很多 html 元素需要使用包含的 JS 函数,并且很难修改每个单独的元素来配置它应该运行哪个函数。
让我们考虑一个简单的例子:我们有生成表的 JSP 标签
<table id="automaticallyGeretatedId">
<tr>
<td></td>
</tr>
</table>
这包括一些 JS 函数
function removeItemFromTable(){
//modify automaticallyGeretatedId
}
function addItemToTable(){
//modify table, add values and so on..
}
然后我们有一些 html 外部按钮或/和 div-s,它们具有常量名称为“clearData”的方法,但 JS 是 HTML 页面的一部分 有时以这种方式(嵌入Html)
<script>
function clearData(){/*some code*/}
</script>
有时在包含文件中为
function clearData(){ //some code
}
所以我的问题是:除了修改代码中每个简单的clearData之外,还有其他方法可以确保每次运行clearData函数时,函数removeItemFromTable()也会运行吗?
我的意思是我可以搜索clearData函数并在调用removeItemFromTable函数后追加吗?这个操作应该在哪里完成,最好的方法是什么?
假设每次出现clearData()函数时,函数removeItemFromTable()也会被包含在内。
最佳答案
最后我决定使用此链接中描述的技术:
Adding code to a javascript function programmatically
我在文档中设置了准备搜索函数clearData()
$( document ).ready(function() {
decorateClearData();
});
以及函数decorateClearData()中的代码;
function decorateClearData() {
clearData = (function() {
var cached_function = someFunction;
return function() {
cached_function.apply(this, arguments); // use .apply() to call it
// and my new code:
removeItemFromTable();
};
}());
}
这是有效的,因为clearData是全局函数,也许这不是务实的方式,但我没有其他想法。
关于javascript - 如何自动处理 javascript 函数调用并包装/装饰它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25503493/