从变量中选择一个id

时间:2014-10-30 20:34:07

标签: javascript selector

我正在使用带有ruby的websockets,但我的问题是使用javascript。我正在尝试使用pic变量访问img位置。我记得使用“解析”命令,但我不记得在哪里看到它。

<body>
  <div id ="a0">
    <img class = "image" src="">
    <br>
    <p class = "info"></p>
  </div>

  <div id ="a1">
    <img class = "image" src="">
    <br>
    <p class = "info"></p>
  </div>
</body> 



:javascript 
  var msg = {"selector" : "a0", "image" : "image0.jpg", "info" : "picture"};
  var pic = document.getElementById(msg["selector"]);

这是问题

  pic.select(".image").src = msg["image"];
  pic.select(".info").innerHTML = msg["info"];

2 个答案:

答案 0 :(得分:0)

<body>
  <div id ="a0">
    <img class = "image" src="">
    <br>
    <p class = "info"></p>
  </div>
  <div id ="a1">
    <img class = "image" src="">
    <br>
    <p class = "info"></p>
  </div>
</body> 

试试这个

pic.querySelector(".image").src = msg["image"];
pic.querySelector(".info").innerHTML = msg["info"];

答案 1 :(得分:0)

我明白了。它的方法是&#34; querySelector&#34;

element = document.querySelector(selectors);

pic.querySelector(".image").src = msg["image"];

https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector