Jquery到Pure Vanilla JS

时间:2018-04-28 13:25:42

标签: javascript jquery

我想将这个小script转换为纯vanilla JS

$('input, textarea').focus(function() { 
        $(this).data('placeholder', $(this).attr('placeholder')).attr('placeholder', '');
    }).blur(function() { 
            $(this).attr('placeholder', $(this).data('placeholder'));
});

DEMO

感谢Treast,我现在就在这里......几乎工作得很好:

var elements = document.querySelectorAll('input, textarea');

for(var i = 0; i < elements.length; i++) {
    var element = elements[i];
    element.addEventListener('focus', function() {
        element.setAttribute('data-placeholder', element.getAttribute('placeholder'));
        element.setAttribute('placeholder', '');
    }),
  element.addEventListener('blur', function() {
        element.setAttribute('placeholder', element.getAttribute('data-placeholder'));
        element.setAttribute('data-placeholder', '');
    });
}

DEMO 2

请问好吗?

2 个答案:

答案 0 :(得分:1)

$('input, textarea')将选择所有输入或textarea。使用Vanilla,您无法在元素列表中添加EventListener,因此您需要遍历所有元素。您需要使用querySelectorAll来获取相同的列表。此外,您无法链接addEventListener

所以你的代码将是:

var elements = document.querySelectorAll(&#39; input,textarea&#39;);

for(var i = 0; i < elements.length; i++) {
    var element = elements[i];
    element.addEventListener('focus', function() {
        this.setAttribute('data-placeholder', this.getAttribute('placeholder'));
        this.setAttribute('placeholder', '');
    });
    element.addEventListener('blur', function() {
        this.setAttribute('placeholder', this.getAttribute('data-placeholder'));
        this.setAttribute('data-placeholder', '');
    });
}

答案 1 :(得分:1)

如果需要,请仔细查看上面的Patrick's comment

-

至于将代码转换为vanilla JS,我认为 Demo 2 的唯一问题是未关闭的Button标记。我建议拆分以帮助提高可读性。看看:https://jsfiddle.net/Lebxdrwk/2/

const onFocus = event => {
  const element = event.target;
  const placeholder = element.getAttribute('placeholder');
  element.setAttribute('data-placeholder', placeholder);
  element.setAttribute('placeholder', '');
};

const onBlur = event => {
  const element = event.target;
  const dataPlaceholder = element.getAttribute('data-placeholder');
  element.setAttribute('placeholder', dataPlaceholder);
  element.setAttribute('data-placeholder', '');
}

const addEventListenersToSwapPlaceholders = element => {
  element.addEventListener('focus', onFocus);
  element.addEventListener('blur', onBlur);
}

document.querySelectorAll('input, textarea')
  .forEach(addEventListenersToSwapPlaceholders);