[英]Getting the id of an html on mouseover with only javascript (no jquery)
我的问题是,如果我有一个看起来像......的Text html元素
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
我可以在mouseover事件中检索id(在本例中为1),以便我可以在javascript中使用它来执行其他操作。
不确定我是否能做到这一点,但我希望我能做到。 我所拥有的是一些从xml文档中获取数据的javascript代码。 我有一张500多张卡片的清单,我已经解析并按照经常使用的类别进行存储。 以下是适用于我的问题的相关功能。
var Card = function Card(cardName, subTitle, set, number, rarity, promo, node)
{
this.cardName = cardName;
this.subTitle = subTitle;
this.set = set;
this.number = number;
this.rarity = rarity;
this.promo = promo;
this.node = node;
}
其中节点是卡片列表中的位置,并且由于我开始使用的文档格式按名称按字母顺序包含每张卡片,而不是在逻辑上按集合编号。
Card.prototype.toLink = function()
{
var txt = "";
this.number;
if (this.promo == 'false')
{
var image = this.set.replace(/ /g, "_") + '/' + this.number;
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + "')>";
txt += this.toString() + "</" + "a>";
}
else
{
var image = this.set.replace(/ /g, "_") + '/' + this.rarity + this.number;
var txt = "";
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ')>";
txt += this.toString() + "</a>";
}
return txt;
}
这是我用来填充卡片列表的内容,其名称在悬停时将显示卡片图像。
function populateList () {
for (i = 0; i<cards.length; i++)
document.getElementById('myList').innerHTML += '<li>'+cards[i].toLink()+</li>;
}
我想要做的是使用onmouseover事件检索元素的id,以便我可以检索未保存到值的所有内容。 我意识到我可以将id作为changeImage函数的一部分作为临时解决方法传递,但它涉及重写我的toLink函数和我的changeImage函数以包含第二个参数。 作为一个已婚男人,我已经有足够的论据,可以用每张卡少一张。
总而言之,我想我需要问的是这个,但有没有办法只使用javascript和html来检索元素的id,onmouseover,以便我可以在函数中使用它。 如果你已经通过我的文本和代码墙,我提前感谢你,并希望对我的问题有任何见解。
如果我有一个看起来像......的Text html元素
<a id='1' onmouseover="changeImage('setname/setnumber')">Cardname</a>
我可以在mouseover事件中检索id(在本例中为1),以便我可以在javascript中使用它来执行其他操作。
是的,如果你可以改变链接(看起来你可以):
<a id='1' onmouseover="changeImage('setname/setnumber', this)">Cardname</a>
注意新的参数this
。 在changeImage
,你会得到这样的id
:
function changeImage(foo, element) {
var id = element.id;
// ...
}
查看代码,您将更新此行toLink
:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', this)>";
当然,你也可以直接输入id
:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', " + this.node + ")>";
然后changeImage
将是:
function changeImage(foo, id) {
// ...
}
我没有使用它周围的引号,因为这些ID看起来像数字。 但如果它不是一个可靠的数字,请使用引号:
txt += "<a id='" + this.node + "' onmouseover=changeImage('" + image + ', '" + this.node + "')>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.