使用这个内部循环

时间:2018-01-30 12:28:18

标签: javascript

我正在尝试使用this内部循环,而不使用jQuery。出于某种原因,它不起作用。为什么呢?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="https://google.foo">Google</a>

<script>
    /*
    // Plain JS - Works
    function doSomething() {
        var links = document.querySelectorAll('a');
        for (var i = 0; i < links.length; i++) {
            links[i].href = links[i].href.replace('foo', 'bar');
        }
    }

    // jQuery - Works
    function doSomething() {
        $('a').each(function() {
            $(this).attr('href', $(this).attr('href').replace('foo', 'bar'));
        });
    }
    */

    // Plain JS - Doesn't work
    function doSomething() {
        var links = document.querySelectorAll('a');
        for (var i = 0; i < links.length; i++) {
            this[i].setAttribute('href', this[i].getAttribute('href').replace('foo', 'bar'));
        }
    }

    doSomething();
</script>

2 个答案:

答案 0 :(得分:0)

没有。 this无法工作。你正在迭代一个数组。因此this没有上下文(至少与您使用的数组相关)。

您应该参考当前的数组元素。这是links[i]

links[i].setAttribute('href', links[i].g....

答案 1 :(得分:0)

在控制台中尝试此功能。您将看到它返回窗口对象。然后,您可以单击窗口对象并检查其所有属性。

function doSomething() {
  var links = document.querySelectorAll('a');
  console.log(this);
  return this;
}

this是根据它的范围传递给函数的对象。所以它不等同于jQuery对象。

相关问题