我正在为我的学校制作一个网站(我16岁),我需要当我提交表单时,它可以改变表单本身的内容。
我试着用"this"做一些事情,但它没有工作。有人能帮帮我吗?
<标题>HTML<form class="form-votacao" name="form-votacao">
<div class="participant-box">
<img src="../images/blank.png" alt="blank" />
<p id="name">participant name undefined</p>
<p id="category">participant category undefined</p>
<p id="talent-info">talent info undefined</p>
<input
type="submit"
value="VOTAR"
name="vote-button"
id="vote-button"
/>
</div>
</form>
<标题>JAVASCRIPT h1>As there will be several divs with the ".participant-box" class inside the form, I would like you to change only the div that I click on the submit button
标题>标题>
首先,我将按钮的类型更改为button
,因为如果您将其类型更改为submit
,那么表单将被提交,因此javascript将是无用的。
下面的代码是使用javascript改变父div的背景,通过点击里面的按钮。
请点击Run code snippet
按钮进行演示。
const buttons = document.querySelectorAll('.vote-button');
buttons.forEach(button => {
button.addEventListener('click', function() {
this.parentElement.style.backgroundColor = 'green';
});
});
<form class="form-votacao" name="form-votacao">
<div class="participant-box">
<p id="name">participant name undefined</p>
<p id="category">participant category undefined</p>
<p id="talent-info">talent info undefined</p>
<input
type="button"
value="VOTAR"
name="vote-button"
id="vote-button"
class="vote-button"
/>
</div>
<br/><br/>
<div class="participant-box">
<p id="name">participant name undefined</p>
<p id="category">participant category undefined</p>
<p id="talent-info">talent info undefined</p>
<input
type="button"
value="VOTAR"
name="vote-button"
id="vote-button"
class="vote-button"
/>
</div>
<br/><br/>
<div class="participant-box">
<p id="name">participant name undefined</p>
<p id="category">participant category undefined</p>
<p id="talent-info">talent info undefined</p>
<input
type="button"
value="VOTAR"
name="vote-button"
id="vote-button"
class="vote-button"
/>
</div>
</form>
我希望我理解你的处境。