根据数组插入html

时间:2016-08-08 16:24:17

标签: javascript html arrays loops for-loop

第12-22行

函数openManu当前在加载时显示一个块,并为我的数组生成 for 循环。然后,它会根据数组创建一个obj变量,并从调用该函数的链接定义的数组中获取Manufacturer。因此,我的HTML中的链接例如将onMouseOver事件绑定到openManu('manufacturer'),并且manu将被定义为制造商,只有与此制造商对应的数组中的“描述”才会插入到HTML中

我的问题是我正在尝试创建另一个在此之前运行的函数,该函数通过我的数组并根据数组中的内容创建链接。然后,一旦主体加载,就会调用链接,链接也会出现onMouseOver事件,其中可以调用第12-22行的第二个函数。

目前只有openManu()有效onMouseOver,并会根据指定的制造商将Description插入我的 HTML 内容中的对象中。我有createLinks()函数打开数组并将URL定义为变量并将其插入到创建的链接标记中。

这可能吗?订单搞砸了吗?

的javascript:

var arr =   
[
  {
    "Manufacturer": "Any manufacturer",
    "Description": "Traditional values",
    "URL": "http://www.website.com"
  },
  {
    "Manufacturer": "Different Manufacturer",
    "Description": "Short description of said manufacturer",
    "URL": "http://www.website2.com"
  },
  {
    "Manufacturer": "A Similar Manufacturer",
    "Description": "Not quite the same as the previous manufacturer",
    "URL": "http://www.website3.com"
  },
  {
    "Manufacturer": "Manufacturer",
    "Description": "Essentially a ripoff of the first manufacturer",
    "URL": "http://www.website4.com"
  }
]

function createLinks() {
    for (var i=0; i<arr.length; i++){
      var obj = arr[i];
      var m = obj["Manufacturer"];
      if (manu == m) {
        URL = obj["URL"];
      }
    }
    document.getElementById('col').innerHTML = "<a onmouseover=\"openManu(\'" ++ m ++ "\')\" onmouseout=\"mouseOut()\" onClick=\"openWeb(\'" ++ URL ++ "\')\">" ++ m ++ "</a>");
}

function openManu(manu) {
  document.getElementById('content').style.display = 'block';
    for (var i=0; i<arr.length; i++){
      var obj = arr[i];
      var m = obj["Manufacturer"];
      if (manu == m) {
        desc = obj["Description"];  
      }
    }
    document.getElementById('content').innerHTML = desc;
}

window.onmousemove = function (e) {
    var tooltipSpan = document.getElementById('content');
    var x = e.clientX,
        y = e.clientY;
    tooltipSpan.style.top = (y - 20) + 'px';
    tooltipSpan.style.left = x + 'px';
}

var mouseOut = function(){
    document.getElementById('content').style.display = 'none'
}

function openWeb(URL) {
    window.open(URL);
}
#container{
width:870px;
margin-top:2em;
font-size:1.1em;
position:relative;
padding-left:20px;
display:inline-block;
background-color:#3C3C4E;}

#content{
z-index:1;
display:none;
width:300px;
font-size:16px;
font-family: 'Raleway', sans-serif;
position:absolute;
padding:10px;
background-color:white;}

a {
cursor:pointer;
padding:0;
display:inline-block;
margin:0;
color: white;
font-family: 'Raleway', sans-serif;
position:inherit;
}

h4 {
padding:0;
z-index:0;
display:inline-block;
margin:0;
color: white;
font-family: 'Raleway', sans-serif;
font-weight:normal;
font-size:15px;
background-color:#3C3C4E;
position:absolute;
left:8px;
padding:24px;
top:400px;
width:842px;
}

pre {
display:block;
float:left;
line-height:21px;
}
<!DOCTYPE html>
<html onload="createLinks()">

<div id="content"></div>

<pre id="col"></pre>

</html>

旧的HTML包含看起来像这样的链接。

<a onmouseover="openManu('Any manufacturer')" onmouseout="mouseOut()" onClick="openWeb('http://www.website.com/')">Any manufacturer</a>

@ Zer00ne在回答你的回答时,我将createLinks()更改为此。我无法让它工作我可能无法完全理解你的解决方案。

function createLinks() {
  arr[i]["Manufacturer"]
  var obj = arr[i];
  var m = obj["Manufacturer"];
  document.getElementById('col').innerHTML = "<a onmouseover=\"openManu(\'" ++ m ++ "\')\" onmouseout=\"mouseOut()\" onClick=\"openWeb(\'" ++ URL ++ "\')\">" ++ m ++ "</a>");
}

JSFiddle

2 个答案:

答案 0 :(得分:2)

乍一看,createLinks函数中的字符串变量连接格式不正确。

function createLinks() {
    for (var i=0; i<arr.length; i++){
      var obj = arr[i];
      var m = obj["Manufacturer"];
      if (manu == m) {
        URL = obj["URL"];
      }
    }
    //document.getElementById('col').innerHTML = "<a onmouseover=\"openManu(\'" ++ m ++ "\')\" onmouseout=\"mouseOut()\" onClick=\"openWeb(\'" ++ URL ++ "\')\">" ++ m ++ "</a>");

// should be.
document.getElementById('col').innerHTML = "<a onmouseover=\"openManu(" + m + ") onmouseout=\"mouseOut()\" onClick=\"openWeb(" + URL + ") >" + m + "</a>";
}

// Although m and URL are never defined.

我也不确定您是否尝试将变量或字符串传递给openMenu函数,但我发现您正在检查if语句中的参数。

    function openManu(manu) {
      document.getElementById('content').style.display = 'block';
        for (var i=0; i<arr.length; i++){
          var obj = arr[i];
          var m = obj["Manufacturer"];
          if (manu == m) { 
            /* 
This will never be true because your argument (manu) comes from whatever you are passing into your function which appears to be a string based on your code. The m that is being assigned from the obj will never be 'm' based on the code. It will be the value that is assigned to the "Manufacturer" key of the object."
*/
            desc = obj["Description"];  
          }
        }
        document.getElementById('content').innerHTML = desc;
    }

我希望这对于正在发生的事情是一个良好的开端。

更新 - 这项工作

这个代码基于您的JSFiddle代码。

HTML

<body onload="createLinks()">

<div id="container">
<pre id="col"></pre>
</div>
<div id="content2"></div>
</body>

CSS

#container{
width:300px;
margin-top:2em;
font-size:1.1em;
position:relative;
display:inline-block;
background-color:#3C3C4E;}


#content{
display:none;
width:300px;
height: 45px;
font-size:16px;
font-family: 'Raleway', sans-serif;
padding:10px;
background-color:white;
}

#col a{
  display:block;
  padding-left:20px;
}
a {
cursor:pointer;
padding:0;
display:inline-block;
margin:0;
color: white;
font-family: 'Raleway', sans-serif;
position:inherit;
}

h4 {
padding:0;
z-index:0;
display:inline-block;
margin:0;
color: white;
font-family: 'Raleway', sans-serif;
font-weight:normal;
font-size:15px;
background-color:#3C3C4E;
position:absolute;
left:8px;
padding:24px;
top:400px;
width:842px;
}

pre {
display:block;
float:left;
line-height:21px;
}

的JavaScript

var arr =   
[
  {
    "Manufacturer": "Any manufacturer",
    "Description": "Traditional values",
    "URL": "http://www.website.com"
  },
  {
    "Manufacturer": "Different Manufacturer",
    "Description": "Short description of said manufacturer",
    "URL": "http://www.website2.com"
  },
  {
    "Manufacturer": "A Similar Manufacturer",
    "Description": "Not quite the same as the previous manufacturer",
    "URL": "http://www.website3.com"
  },
  {
    "Manufacturer": "Manufacturer",
    "Description": "Essentially a ripoff of the first manufacturer",
    "URL": "http://www.website4.com"
  }
];

// cache the col element
var col = document.getElementById("col")
// The forEach loop goes through the array 
arr.forEach( function(key, idx){ // grab the key an dthe index
    var newAchr = document.createElement("a"); // create an anchor DOM element
    newAchr.href = key.URL; // assign the href for the element
    newAchr.text = key.Manufacturer; // assign the text
    newAchr.setAttribute("class", idx); // assign a class that will store the index. This will be used to get the description on mouseover.

    document.getElementById('col').appendChild(newAchr); // apend the element to the DOM
});

col.addEventListener("mouseover", function(e){
    var target = e.target, //get the currently targeted anchor tag
        idx = target.classList[0], // get the index that wsa stored inthe elements class
        desc = arr[idx].Description, // get the description from the array usinf the index from the class
        contentElem = document.getElementById('content2'); // get a reference to the content element

    contentElem.style.display = "block"; // display the content area
    contentElem.innerHTML = desc; // add the discription text to the content area
});

col.addEventListener("mouseout", function(e){
    var contentElem = document.getElementById('content2'); // get a reference to the content area

    contentElem.style.display = "none"; // hide the content area on mouseout
});

答案 1 :(得分:1)

更新

添加了工具提示,我意识到你的意图是什么,现在跟着光标#content。这可以解释我遇到麻烦的古怪风格。

我修复了它,这个概念很健全,代码需要大量的工作。我删除了mousemove事件处理程序,因为当您已在#content中显示说明时,没有任何工具提示。以下代码段在/* comments */ // comments

中有说明

&#13;
&#13;
/* Wrapped in an anonymous function to avoid globals */
(function() {
  var mfc = [{
    "Manufacturer": "Any manufacturer",
    "Description": "Traditional values",
    "URL": "http://www.website.com"
  }, {
    "Manufacturer": "Different Manufacturer",
    "Description": "Short description of said manufacturer",
    "URL": "http://www.website2.com"
  }, {
    "Manufacturer": "A Similar Manufacturer",
    "Description": "Not quite the same as the previous manufacturer",
    "URL": "http://www.website3.com"
  }, {
    "Manufacturer": "Manufacturer",
    "Description": "Essentially a ripoff of the first manufacturer",
    "URL": "http://www.website4.com"
  }];

  /* It's better to declare variable of 'for' loop outside of loop */
  var i, len = mfc.length;


  for (i = 0; i < len; i++) {
    // Use of bracket notation requires quotes 
    var m = mfc[i]["Manufacturer"];
    var URL = mfc[i]["URL"];
    var desc = mfc[i]["Description"];
    var col = document.getElementById('col');
    /*
    /| When concatenating strings, alternate between single and double
    /| quotes and don't double up on '+'
    */
    // title attribute will be "Description"
    // Just use href attribute instead of a function that does the same thing (i.e. openWeb(URL)
    // The text of an anchor is m
    /* 
    /| Notice the '+=' operand, this allows us to accumulate strings 
    /| instead of overwriting them on every loop. 
    */
    col.innerHTML += '<a title="' + desc + '" href="' + URL + '">' + m + '</a>';
  }
  var content = document.getElementById('content');


  /*
  /| Instead of attribute events, use addEventListener() on the 
  /| parent of the links (i.e. #col). In order to determine which anchor
  /| was clicked, you assign a var to event.target.
  */

  col.addEventListener("mouseover", function(e) {
    // Find the e.target (i.e. element that was hovered over), and get it's title
    // display content with desc as it's content.
    var desc = e.target.getAttribute('title');
    content.style.display = "block";
    content.innerHTML = desc;
  }, false);

  col.addEventListener("mouseleave", function(e) {
    content.style.display = "none";
  }, false);


  col.addEventListener("mousemove", function(e) {
    var x = e.clientX,
      y = e.clientY;
    content.style.top = (y - 20) + 'px';
    content.style.left = x + 'px';
  }, false);

})();
&#13;
#container {
  width: 870px;
  line-height: 1.2;
  margin-top: 2em;
  font-size: 1.1em;
  position: relative;
  padding-left: 20px;
  display: inline-block;
  background-color: #3C3C4E;
}
#content {
  z-index: 0;
  display: none;
  width: 400px;
  font-size: 16px;
  font-family: 'Raleway', sans-serif;
  position: absolute;
  padding: 10px;
  color: white;
  background-color: black;
  top: 0;
}
col {
  position: absolute;
  top: 70px;
}
a {
  cursor: pointer;
  padding: 0;
  display: inine-block;
  margin: 0 5px;
  color: white;
  font-family: 'Raleway', sans-serif;
}
h4 {
  padding: 0;
  z-index: 0;
  display: inline-block;
  margin: 0;
  color: white;
  font-family: 'Raleway', sans-serif;
  font-weight: normal;
  font-size: 15px;
  background-color: #3C3C4E;
  position: absolute;
  left: 8px;
  padding: 24px;
  top: 400px;
  width: 842px;
}
pre {
  display: block;
  float: left;
  line-height: 21px;
}
&#13;
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>

  <div id="container">
    <div id="content"></div>
    <div id="col">
    </div>
  </div>
</body>

</html>
&#13;
&#13;
&#13;