gpt4 book ai didi

javascript - 单击时更改图像和文本值

转载 作者:行者123 更新时间:2023-11-28 01:10:10 27 4
gpt4 key购买 nike

所以,我有 3 个变量,如下所示,假设它们已被赋值。我想要做的是当用户单击 div class="info2"时将这些变量插入到 img class "myimg2"、p class "myname2"和 p class "myprof2"中。

它必须位于该 div 中,因为我希望用户单击该 div 上的任意位置来更改所有 3 个值。

这在 JavaScript 中可能吗?

JavaScript:

var storeOnClick, 
name,
prof;

HTML

<table class="table2" rules="rows">
<tr>
<td>
<div class="info2" onclick="changeStats(this)" >
<div style="float:left">
<img class="myimg2"style="max-height:80px;" src="Pictures/QuestionMark.png">
</div>
<div style="float:left;">
<p class="myname2">Name: Jane Doe</p>
<p class="myprof2">Profession: Something</p>
</div>
</div>
</td>
<td>
<div class="info2" onclick="changeStats(this)" >
<div style="float:left">
<img class="myimg2"style="max-height:80px;" src="Pictures/QuestionMark.png">
</div>
<div style="float:left;">
<p class="myname2">Name: Jane Doe</p>
<p class="myprof2">Profession: Something</p>
</div>
</div>
</td>
</tr>
</table>

最佳答案

好的,我想我已经得到了代码。我这样做的方式是将事件处理程序附加到页面的body。然后在该函数中,我检测您是否单击了 .info 元素(或其子元素之一)。如果您这样做了,那么我会更改该特定 .info div

的值

super 重要的部分:

// add an event listener to the entire body. I could have iterated through each div with the '.info2' class instead
if (document.body.addEventListener) {
document.body.addEventListener('click', updateCard, false);
} else {
document.body.attachEvent('onclick',updateCard); // stupid IE
}


// this is the callback function for the click event handler
function updateCard(e) {
e = e || window.event;
var target = e.target || e.srcElement; // more IE stuff

// does target have an ancestor of .info2 ?
var el = findAncestor(target, 'info2');
if (el) {

// which elements do we want to update? Only the currently clicked on .info2
var iImg = el.querySelector('.myimg2');
var iName = el.querySelector('.myname2');
var iProf = el.querySelector('.myprof2');


// assign the values a random element from the arrays
storeOnClick = imgArray[Math.floor(Math.random()*imgArray.length)];
name = nameArray[Math.floor(Math.random()*nameArray.length)];
prof = profArray[Math.floor(Math.random()*profArray.length)];


iImg.src = storeOnClick;
iName.innerHTML = lblName + name;
iProf.innerHTML = lblProf + prof;
}
}

// this is similar to jQuery's $.parents('.class')
function findAncestor (el, cls) {
while ((el = el.parentElement) && !el.classList.contains(cls));
return el;
}

demo

为了好玩,下面是它在 jQuery 中的样子:

$(function() {
$('.info2').on("click",function() {
var t = $(this);
t.find('.myimg2').attr('src',storeOnClick);
t.find('.myname2').html(name);
t.find('.prof2').html(prof);
});
});

关于javascript - 单击时更改图像和文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24545149/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com