簡體   English   中英

如何使用選擇器作為該功能的目標

[英]how do I use a selector as a target for that function

可能非常簡單,但是我似乎無法弄清楚該怎么做:

function mouseOver(i,x){document.x.src="img/"+x+"/pic"+i+".jpg";}

document.x.srcx假定代表x選擇器,但不是。 如何將x選擇器用作該函數的目標?

額外信息: x是在其他函數中定義的,它將成為文件夾的名稱,在我的情況下為“ refugeelive”。 我還想將目標img命名為“ refugeelive”,這是此功能的目標。 這樣,通過將x定義為“ refugeelive”,可以從正確的文件夾中選擇img,並將其發送到正確的目標img。

不能明確解決問題,但是您可以在此基礎上進行改進(或改進)

<head>
<style>
div.myDiv {
  width: 100px;
  min-width: 100px;
  height: 100px;
  min-height: 100px;
  background-color: yellow;
}
</style>
</head>
<body>
<div class="myDiv"></div>
<script>
document.querySelector('.myDiv').addEventListener('mouseover',
function(e) {
    if(e.target.id)
      console.log(e.target.tagName.toLowerCase() + '#' + e.target.id);
    if(e.target.className)
      console.log(e.target.tagName.toLowerCase() + '.' + e.target.className);
});
</script>
</body>

在JavaScript中, object.property始終與object['property'] ,因此:

document[x].src

但是直接從document訪問頁面元素是一種不好的做法(在某些瀏覽器模式下可能會失敗)。 最好使用document.getElementById(x) (並確保您使用的是id="refugeelive"而不是古老的name="refugeelive" )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM