javascript - 最后一步排序错误。函数获取颜色

标签 javascript html function sorting wrapper

当我发送一个变量作为前一个函数的包装时,我无法理解我做错了什么。

函数 GetColor 必须在输入处接收两个值(变量排序变量 a),然后比较它们。如果 a[i].getAttribute('href') 的某些值与 sort[i] 的值匹配 - 打印这些 标签 a 在屏幕上,并在 DOM 内以黄色绘制这些标签 a

现在,我对 GetSort 函数中先前丢弃的值 "http://internal.com/" 的 GetColor 输出进行了奇怪的排序。

我认为错误在于我对传递函数参数的了解不够。

我将感谢您的帮助。

<script>

    let a = document.body.getElementsByTagName('a');

    function getList(list) { // creating an array from all a tag elements.

        let arr = [];
        for (let i = 0; i < a.length; i++) {

            if (a[i].getAttribute('href')) {
                arr.push(a[i].getAttribute('href'));        

            }
        }

        return arr;
    };

    function getSort(f) { // sort array given from getList() by symbols 'http'...

      let sorting;
      let arr = [];
      for (let i = 0; i < f.length; i++) {

         if (f[i].includes('://') && !f[i].includes('http://internal.com/')) {
            console.log(f[i]);
            arr.push(f[i]);
         }
      }

      return arr; // [ "http://google.com" , "ftp://ftp.com/my.zip" , 
                    // "http://nodejs.org" ]
    };

    let sort = getSort(getList());

    console.log(sort);

    function getColor(sort) { // paint a tags based on sort elements from getSort()

        for (let i = 0; i < a.length; i++) {
            if (a[i].getAttribute('href') == sort[i]) {
                a[i].setAttribute('class', 'external'); // paint sorted a tags in DOM  
                                                        // by [external] attribute
                console.log(a[i]);

            }
        }
        return a;
    }

    getColor(a);



</script>

HTML:

<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
<style>
  .external {
    background-color: yellow
  }
</style>

</head>

<body>
<a name="list">list</a>
<ul>
  <li><a href="http://google.com">http://google.com</a></li>
  <li><a href="/tutorial">/tutorial.html</a></li>
  <li><a href="local/path">local/path</a></li>
  <li><a href="ftp://ftp.com/my.zip">ftp://ftp.com/my.zip</a></li>
  <li><a href="http://nodejs.org">http://nodejs.org</a></li>
  <li><a href="http://internal.com/test">http://internal.com/</a></li>
</ul>


</body>

</html>

最佳答案

好的。

如果添加一些日志语句,您可以准确地看到发生了什么:

    let a = document.body.getElementsByTagName('a');

    function getList(list) { // creating an array from all a tag elements.

        let arr = [];
        for (let i = 0; i < a.length; i++) {

            if (a[i].getAttribute('href')) {
                arr.push(a[i].getAttribute('href'));        

            }
        }

        return arr;
    };

    function getSort(f) { // sort array given from getList() by symbols 'http'...

      let sorting;
      let arr = [];
      for (let i = 0; i < f.length; i++) {

         if (f[i].includes('://') && !f[i].includes('http://internal.com/')) {
            console.log(f[i]);
            arr.push(f[i]);
         }
      }

      return arr; // [ "http://google.com" , "ftp://ftp.com/my.zip" , 
                    // "http://nodejs.org" ]
    };

    let sort = getSort(getList());

    function getColor(sort) { // paint a tags based on sort elements from getSort()

        for (let i = 0; i < a.length; i++) {
			console.log( 'a' );
			console.log( a[ i ] );
			console.log( a[ i ].getAttribute( 'href' ) );
			console.log( 'sort' );
			console.log( sort[ i ] );
			console.log( sort[ i ].toString() );
			console.log( a[ i ].getAttribute( 'href' ) == sort[ i ] );
			console.log( '-----' );
            if (a[i].getAttribute('href') == sort[i]) {
                a[i].setAttribute('class', 'yellow'); // paint sorted a tags in DOM  
                                                        // by [external] attribute
            }
        }
        return a;
    }

    getColor(a);
.yellow {
  background-color: yellow
}
<a name="list">list</a>
<ul>
  <li><a href="http://google.com">http://google.com</a></li>
  <li><a href="/tutorial">/tutorial.html</a></li>
  <li><a href="local/path">local/path</a></li>
  <li><a href="ftp://ftp.com/my.zip">ftp://ftp.com/my.zip</a></li>
  <li><a href="http://nodejs.org">http://nodejs.org</a></li>
  <li><a href="http://internal.com/test">http://internal.com/</a></li>
</ul>

a 是在函数外部定义的节点列表。 然后使用 getSort()

创建 sort 数组

最后,您使用 a 而不是 sort 调用 getColor()

所以基本上你是在将 a 与其自身进行比较。

由于a包含html节点,因此sort也包含html节点。

因此,当您使用 a[i].getAttribute( 'href' ) 时,您会得到一个字符串。 然后将该字符串与其自己的节点进行比较。 由于您使用的是 == (比较值)而不是 === (comapre 值和类型),因此 sort 中的节点(其中与 a 中的节点相同)将调用其自己的 toString() 函数将其转换为字符串。

正如您在我添加的 console.log 语句中看到的,如果链接不包含 href 属性,则其末尾会带有 /然而(如 http://internal.com/test )

由于 http://google.com/http://google.com 不同,因此结果为 false。与 http://nodejs.org/http://nodejs.org 相同。

因此只有 ftp://ftp.com/my.ziphttp://internal.com/test 满足条件并以黄色打印。

如果我必须写这个,我会写这样的东西。 它不包括功能,但显示了我要遵循的工作流程。

// 0) Get the array of tag elements.
const hyperlinks = document.querySelectorAll( 'a' );

// 1) Creating an array from all a tag elements.
const ary_hyperlinks = Array.from( hyperlinks );
// If your browser doesn't support Array.from(), you can use the slice method.
// const ary_hyperlinks = Array.prototype.slice.call( hyperlinks );

// 2) Sort array given from getList() by symbols 'http'.
// Since your code doesn't actually do any SORTING as we understand sorting, i'll just write what I think the question is.
// Since the assignment doesn't actually say that you have to reorder the elements in sorted order, this operation basically does nothing.
// If you have to reoder the elements while you color them yellow, we'd need to adjust the code.
const sorted_filtered_hyperlinks = ary_hyperlinks
  // Filter out all links that don't have a href attribute including http, ftp and that are not internal.
  .filter( function( node ) {
    const uri = node.getAttribute( 'href' );
    if ( uri ) return !uri.includes( 'internal' ) && uri.includes( 'http' ) || uri.includes( 'ftp' );
    else return false;
  } )
  // Sort the links by type. Since the type is the start of the href attribute of the link, this comes down to sorting the urls alphabetically
  .sort( function( first, second ) {
    // Alphabetically earlier eltters are smaller than later letters.
    if ( first.getAttribute( 'href' ) < second.getAttribute( 'href' ) ) return 1;
    else return -1;
  } );	

// 3) paint a tags based on sort elements from getSort()
sorted_filtered_hyperlinks.forEach( function( node ) {
  node.setAttribute( 'class', 'yellow' );
} );
.yellow {
  background-color: yellow
}
<a name="list">list</a>
<ul>
  <li><a href="http://google.com">http://google.com</a></li>
  <li><a href="/tutorial">/tutorial.html</a></li>
  <li><a href="local/path">local/path</a></li>
  <li><a href="ftp://ftp.com/my.zip">ftp://ftp.com/my.zip</a></li>
  <li><a href="http://nodejs.org">http://nodejs.org</a></li>
  <li><a href="http://internal.com/test">http://internal.com/</a></li>
</ul>

关于javascript - 最后一步排序错误。函数获取颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48322974/

相关文章:

objective-c - 目标 - C -> 将数组作为函数参数传递

将变量作为参数的默认值的 PHP 函数

javascript - QUnit.test 在 for 循环中运行

javascript - 为什么这个 addEventListener 不适用于我创建的 li 元素?

php - 裁剪图像无法正常工作,存储了错误的部分

javascript - 如何禁用 HTML/JS 中的 STYLE 元素?

javascript - 无法将输入数据发送到函数并将其作为表返回

javascript - 根据值将表单提交到 URL

Javascript,X-Editable 仅更新第一个提交的数据,但不更新第二个

matlab - 如何识别生成特定工作区变量的脚本?