如何使用jquery将新添加的元素存储在变量中?

时间:2018-01-25 10:04:53

标签: jquery

当我控制newNode时,它仍然打印父,为什么?



function appendNewStage() {
  var parent = $('.ci-journey-interactions-canvas_row');
  var newStage = `<ul class="ci-journey-interactions-canvas__journey-list 
                    stage">
                  <li>
                    <span class="ci-journey-interactions-box__droppable-
                     element ci-droppable"></span>
                  </li>
                </ul>`;
  var newNode = $(parent).append(newStage);
  console.log(newNode.html());
}
appendNewStage()
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="ci-journey-interactions-canvas_row"></div>
&#13;
&#13;
&#13;

4 个答案:

答案 0 :(得分:1)

试试这个,

var newNode = $(newStage).appendTo(".ci-journey-interactions-canvas_row");

答案 1 :(得分:0)

不需要让父对象直接使用它

function appendNewStage(){
var parent = $('.ci-journey-interactions-canvas_row');
var newStage = `<ul class="ci-journey-interactions-canvas__journey-list 
                stage">
              <li>
                <span class="ci-journey-interactions-box__droppable-
                 element ci-droppable"></span>
              </li>
            </ul>`;
var newNode = parent.append(newStage);
 console.log(newNode);
} 

答案 2 :(得分:0)

原始代码效果很好。单击代码段中的按钮以添加新阶段

function appendNewStage() {
  var parent = $('.ci-journey-interactions-canvas_row');
  var newStage = `<ul class="ci-journey-interactions-canvas__journey-list 
                    stage">
                  <li>
                    <span class="ci-journey-interactions-box__droppable-
                     element ci-droppable"></span>
                  </li>
                </ul>`;
  var newNode = $(parent).append(newStage);
  console.log(newNode.html());
}
appendNewStage()  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button onclick="appendNewStage()">add a new stage </button>

<div class="ci-journey-interactions-canvas_row"></div>

答案 3 :(得分:0)

.ci-journey-interactions-canvas_row的最后一个元素是附加元素。也许您可以全局使用newNode变量,以便在其他函数中使用它。

var newNode = null;

function appendNewStage() {
  var parent = $('.ci-journey-interactions-canvas_row');
  var newStage = `<ul class="ci-journey-interactions-canvas__journey-list 
                    stage">
                  <li>
                    <span class="ci-journey-interactions-box__droppable-
                     element ci-droppable"></span>
                  </li>
                </ul>`;
  $(parent).append(newStage);
  newNode = $(parent).find('ul:last-child').parent().html();
}