亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

輸入未添加到數組(初學者)JavaScript

輸入未添加到數組(初學者)JavaScript

皈依舞 2023-04-20 10:40:08
當文本寫入輸入框然后單擊按鈕時,我希望將文本(值)添加到我為其創建的數組中(該數組稱為“主題”)。未添加輸入框中的文本(值)...為什么?var subject = [];function addSubjects() {  namesInputted = document.getElementById('namesInputter').value;  subject.push(namesInputted);  console.log(subject);}<!DOCTYPE html><html dir="ltr"><head>  <meta charset="utf-8">  <title>Prueva tu Suerte</title>  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">  <link rel="stylesheet" href="styles.css"></head><body>  <form class="" action="index.html" method="post">    <input type="text" id="namesInputter" value="">    <button onclick="addSubjects()">Add Player</button>  </form>  <span id='S'></span>  <span id='V'></span>  <span id='O'></span>  <span id='P'></span>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>  <script src="function.js"></script></body></html>
查看完整描述

2 回答

?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

實際上,您的代碼正在運行。輸入值附加到array. 但問題是,你正在使用form。所以當你點擊按鈕時,它會在添加值后立即提交表單array。因此頁面將刷新并且array將變為空。


form如果您不想提交數據,只需刪除標簽。


var subject = [];

function addSubjects() {

  namesInputted = document.getElementById('namesInputter').value;

  subject.push(namesInputted);

  console.log(subject);

}

<!DOCTYPE html>

<html dir="ltr">


<head>

  <meta charset="utf-8">

  <title>Prueva tu Suerte</title>

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">

  <link rel="stylesheet" href="styles.css">

</head>


<body>

  <input type="text" id="namesInputter" value="">

  <button onclick="addSubjects()">Add Player</button>

  <span id='S'></span>

  <span id='V'></span>

  <span id='O'></span>

  <span id='P'></span>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

  <script src="function.js"></script>

</body>


</html>


查看完整回答
反對 回復 2023-04-20
?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

如果你想使用 jQuery 的表單提交,你可以這樣使用:


HTML


<form>

  <input type="text" id="namesInputter" value="">

  <button type="submit">Add Player</button>

</form>

JavaScript


var subject = [];

function addSubjects(e) {

}


$("form").submit(function(e){

  e.preventDefault();

  namesInputted = document.getElementById('namesInputter').value;

  subject.push(namesInputted);

  console.log(subject);

});


查看完整回答
反對 回復 2023-04-20
  • 2 回答
  • 0 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號