1

При нажатии на "add test" внутри div с id test_container появляется div с классом q. Внутри которого появляется input и сбоку button с классом add_ans. При нажатии на этот button внутри div с классом q появляются input с классом answer_input - как варианты ответов.

Проблема в том, что input для вариантов ответов добавляются, только, в случае клика на первый button, который был создан статически, А мне нужно чтобы с каждого button соответствующим input который создаётся динамически запускалась эта функция.

function add_test() {
  var question = document.getElementsByClassName("question_container");
  var q = document.createElement("div");
  q.setAttribute("class", "q");

  var span = document.createElement("span");
  span.innerHTML = "Add question";

  q.appendChild(span);

  var input = document.createElement("input");
  input.setAttribute("type", "text");
  input.setAttribute("class", "question_input");

  var button = document.createElement("button");
  button.setAttribute("class", "add_ans");
  button.innerHTML = "+";

  q.appendChild(input);
  q.appendChild(button);

  for (var i = 0; i < question.length; i++) {
    question[i].appendChild(q);
  }
}

function add_answer() {
  var q_ans = document.getElementsByClassName("q");
  var question_container = document.getElementsByClassName("question_container");

  var input_ans = document.createElement("input");
  input_ans.setAttribute("type", "text");
  input_ans.setAttribute("class", "answer_input");

  //alert(question_container[0].children[1]);
  for (var i = 0; i < question_container.length; i++) {
    for (var k = 0; k < q_ans.length; k++)
      question_container[i].children[k].appendChild(input_ans);
  }
}
* {
  margin: 0px;
}

#test_container {
  width: 200px;
  padding: 5px;
  border: 2px solid black;
}

.q {
  display: inline-block;
}

.question_container span {
  color: red;
}

.question_container {
  display: inline-block;
  padding-top: 5px;
  padding-bottom: 5px;
  border: 1px solid red;
  display: inline-block;
}
<div id="test_container">
  <button onclick="add_test()">Add test</button>
  <div class="question_container">
    <div class="q">
      <span>Add question</span>
      <input type="text" class="question_input" name="question" />
      <button class="add_ans" onclick="add_answer()"> + </button>
    </div>
  </div>
  <button>Save test</button>

1 ответ 1

0

Почитайте про bubbling.

Слушайте событие click на общем родителе. Проверяйте что кликнули по правильному элементу и выполняйте добавление ответа.

function add_test() 
{
    
        


        var question=document.getElementsByClassName("question_container");
        var q=document.createElement("div");
        q.setAttribute("class","q");


        var span=document.createElement("span");
        span.innerHTML="Add question";

        q.appendChild(span);

        var input=document.createElement("input");
        input.setAttribute("type","text");
        input.setAttribute("class", "question_input");


        var button=document.createElement("button");
        button.setAttribute("class", "add_ans");
        button.innerHTML="+";

        q.appendChild(input);
        q.appendChild(button);

        

    for (var i = 0; i<question.length; i++) 
    {

        question[i].appendChild(q);
    }





}




function add_answer( button ) 
{
    var q_ans = button.parentNode

    var input_ans=document.createElement("input");
    input_ans.setAttribute("type","text");
    input_ans.setAttribute("class", "answer_input");
    
    q_ans.insertBefore( input_ans, button );
         

}
    
document.body.addEventListener('click', function( ev ){
	 var node = ev.target;
   if( ! node.classList.contains('add_ans') ) return;
   
   add_answer( node );
   
}, true)
<title>Document</title>
<body>
<div id = "test_container">

  <button onclick="add_test()">Add test</button>

   <div class="question_container">
     <div class="q">
        <span>Add question</span>
        <input type="text" name="question">
        <button class = "add_ans" >+</button>
     </div>
   </div>
</div>

<button>Save test</button>
</body>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.