简体   繁体   English

用另一个元素替换HTML元素

[英]Replace HTML element with another element

I'm trying to get an img element with an id of origImg to turn into an iframe element with the id video when certain keys are pressed. 我试图让一个img元素用的ID origImg变成一个iframe和id元素video时按下某些键。 I don't know any javascript, so how can i do this? 我不知道任何JavaScript,所以我该怎么做?

  1. Bind the keyup event to something that can capture keystrokes, for my example, the document captures keystrokes. 将keyup事件绑定到可以捕获击键的内容,以我的示例为例,该document捕获击键。

  2. Then, evaluate which key was pressed. 然后,评估按下了哪个键。 Simply watching jQuery's event.which will handle browser support. 只需观看jQuery的event即可处理浏览器支持。

  3. Then, use jQuery's .replaceWith() to replace an existing HTML element with a new element. 然后,使用jQuery的.replaceWith()用新元素替换现有的HTML元素。

This should be all you need. 这应该是您所需要的。

Edit 编辑

If you need multiple characters, you need to set their values to an array and check for the existence, super easy. 如果需要多个字符,则需要将它们的值设置为数组并检查是否存在,这非常简单。

var accepted = ['13', '8', '9', '40'];

$(document).on('keyup', function(e){
    if($.inArray(e.which, accepted){
        $('#origImg').replaceWith('<iframe id="video"/>');
    }
});

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

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