覆盖嵌入在html元素中的现有onkeydown

时间:2015-09-23 04:43:21

标签: javascript override onkeydown

在html元素中调用onkeydown函数。:

"<"输入标题="输入值" onkeydown ="返回RadWindowprompt_detectenter(' {0}',event,this);"类型="文本"类=" rwDialogInput"值=" {2}" " />"

但是我需要用document.onkeydown函数覆盖它

    document.addEventListener('keydown', captureEnter, true);

    function captureEnter(evt) {

        evt = evt || window.event;
        if (evt) {
            ele_type = evt.srcElement.getAttribute("id");
            if (!(ele_type == $("[id$='AddNewLink']") || ele_type == $("[id$='Add_New']") || ele_type == $("[id$='AddNewImage']"))) {
                ele_type = null;
                return;
            }

        }

    };

如何让我的函数运行而不是执行嵌入onkeydown的html?

1 个答案:

答案 0 :(得分:0)

如果您不希望onkeydown处理程序执行,我认为您可以停止事件的传播

document.addEventListener('keydown', captureEnter, true);

function captureEnter(evt) {
  snippet.log('captureEnter')
  evt.stopPropagation()
};

function RadWindowprompt_detectenter() {
  snippet.log('RadWindowprompt_detectenter')
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<input title="Enter Value" onkeydown="return RadWindowprompt_detectenter('{0}', event, this);" type="text" class="rwDialogInput" value="{2}"/>

另一种方法是删除onkeydown处理程序,如

document.addEventListener('keydown', captureEnter, true);

function captureEnter(evt) {
  snippet.log('captureEnter')
};


var els = document.querySelectorAll('input.rwDialogInput[onkeydown]');
for (var i = 0; i < els.length; i++) {
  els[i].removeAttribute('onkeydown');
}

function RadWindowprompt_detectenter() {
  snippet.log('RadWindowprompt_detectenter')
}
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

<input title="Enter Value" onkeydown="return RadWindowprompt_detectenter('{0}', event, this);" type="text" class="rwDialogInput" value="{2}" />