在vanilla JavaScript中使用jQuery更改方法? [英] jQuery change method in vanilla JavaScript?

查看:53
本文介绍了在vanilla JavaScript中使用jQuery更改方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面写了一小段使用change方法的jQuery代码。我刚刚发现jQuery不再在项目中使用,所以我需要在Vanilla JS中重新编写change方法。只是寻求一些帮助我如何做到这一点。这是代码,它拉取一个输入的值并将其输入另一个输入。

I wrote a little piece of jQuery code below that uses the change method. I just found out jQuery is no longer being used in the project so I need to re-write the change method in Vanilla JS. Just looking for some assistance on how I can do that. Here is the code, it pulls the value of one input and enters it into another.

(function(){

  $('#Email').change(function() {
    $('#UserName').val($(this).val());
  });

})();


推荐答案

浏览器应根据事件的附加方式而有所不同。你可能想要从一个小帮手方法开始:

Browsers vary on how events should be attached. You'd probably want to start with a little helper method:

function addEventHandler(elem, eventType, handler) {
    if (elem.addEventListener)
        elem.addEventListener (eventType, handler, false);
    else if (elem.attachEvent)
        elem.attachEvent ('on' + eventType, handler); 
}

对于以下示例,我将假设您的IIFE应该有真的是一个DOM-ready活动。代码中的IIFE似乎没有任何用途。所以...

For the following sample, I'm going to assume that your IIFE should have really been a DOM-ready event. The IIFE in your code doesn't seem to really serve any purpose. So...

您的代码中有两个事件,即DOM-ready事件(DOMContentLoaded)和select元素的更改事件(onchange)。利用上面的帮助程序,您的jQuery语法转换为:

There are two events from your code, the DOM-ready event ("DOMContentLoaded") and the select element's change event ("onchange"). Taking advantage of the above helper, your jQuery syntax translates to:

addEventHandler(document, 'DOMContentLoaded', function() {
    addEventHandler(document.getElementById('Email'), 'change', function() {
        document.getElementById('UserName').value = this.value;
    });
});

工作jsFiddle演示

这篇关于在vanilla JavaScript中使用jQuery更改方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆