用div包裹元素

时间:2017-09-25 08:32:00

标签: jquery

的jquery-3.2.1.min.js

我克隆了一个元素,并希望将克隆的元素包装在标记中。

<select name="person_choice" id="id_person_choice">
  <option value="" selected="">---------</option>

  <option value="1">1: Smith </option>

  <option value="2">2: Johnson </option>

</select>

好吧,补充道:

<div><select name="person_choice" id="id_person_choice">
  <option value="" selected="">---------</option>

  <option value="1">1: Smith </option>

  <option value="2">2: Johnson </option>

</select></div>

正如我们所看到的,它没有用div包装。

渴望的是:

.navbar {
  margin: 0;
  padding: 0;
  text-align: center;
  border-bottom: solid #000;
  border-width: 1.5px 0;
  list-style: none;
  height: 25px;
  width: 1000px;
}
.navbar a {
  text-decoration: none;
  padding: 0;
  margin: 10px;
  border-bottom: 10px;
  color: #000;
  text-align: center;
}
li {
  display: inline-block;
  font-family: 'Muli', sans-serif;
  font-size: 19px;
  margin: 0;
  padding: 0;
  text-align: center;
}

/* center */
.nav1 {
  display: -webkit-flex;
  display: flex;

  -webkit-justify-content: center;
  justify-content: center;		

  -webkit-align-items: center;
  align-items: center;

  width: 100%;
  height: auto;		
  
  text-align: center;  
}

.navbar1 {				

  -webkit-align-self: center;							
  align-self: center;
}

li a:hover {
  color: red;
  cursor: pointer;
}
/* || center */

你能帮我理解错误的位置。

1 个答案:

答案 0 :(得分:1)

始终最好read the documentation of the method you're using :: - )

  

此方法返回用于链接目的的原始元素集。

因此,当您添加它时,将其从包装中删除,而不是将其放在新的父级中。

相反,由于您正在处理DOM中不存在的元素,请创建div并添加append

function add_and_keeper(){
    let $and_keepers = $("#and_keepers"); // $and_keepers = [td#and_keepers]
    let $keeper_choice_clone = $person_choice.clone() // $keeper_choice_clone = [select#id_person_choice, prevObject: r.fn.init(1)]
    let $div = $("<div>");
    $div.append($keeper_choice_clone);
    let $new_elem = $and_keepers.append($div).children("select:last-child");
}

如果您愿意,也可以更简洁地写出:

function add_and_keeper(){
    let $and_keepers = $("#and_keepers"); // $and_keepers = [td#and_keepers]
    let $keeper_choice_clone = $person_choice.clone() // $keeper_choice_clone = [select#id_person_choice, prevObject: r.fn.init(1)]
    let $new_elem = $and_keepers.append($("<div>").append($keeper_choice_clone)).children("select:last-child");
}

我倾向于选择前者进行调试。

相关问题