我正尝试使用p
元素或仅具有选定选项的标签替换所有下拉列表,原因是我要准备进行打印而不显示下拉列表中的向下箭头
我需要使用类型选择器,因为select元素具有不同的类名且没有ID。问题是,我在使用$("select")
时似乎无法获得完整的select元素。
我注意到使用$("select")
时得到的结果与在控制台中使用ID选择器时得到的结果不同
$("#id") //return
init {context: document, selector: "#2"}
var allInputs = $("select"); //return
<select id="2">
<option>Option</option>
<option>Option2</option>
</select>
allInputs[key].replaceWith("<p>" + text+ "</p>") //so this doesn't work
这是JS代码的副本
var allInputs = $("select");
if($("#2")==allInputs[0])
{alert("True");}
$.each( allInputs, function(key, value ) {
var text=value.find("option:selected").text() ;
allInputs[key].replaceWith("<p>" + text+ "</p>");
});
Jsfiddle在这里:
答案 0 :(得分:0)
如何使用映射(我是用无序列表完成的,但您知道了)运行下面的代码段
$('#mybutton').click(function() {
$("select").map(function() {
return $(this)
}).get()
.forEach(function(element) {
$('#container').append(
`<ul><li>
${element.val()}<ul>${getOptions(element)}</ul>
</li></ul>`)
});
function getOptions(element) {
let html = ''
element.find('option').map(function() {
return $(this).val();
}).get()
.forEach(function(option) {
html += `<li>${option}</li>`
});
return html;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="file">
<input type="text">
<select id="2">
<option>Option</option>
<option>Option2</option>
</select>
<select>
<option>selector</option>
<option>Option3</option>
</select>
</br>
<button type="button" id="mybutton">
print all options
</button>
</form>
<div id="container">
</div>
答案 1 :(得分:0)
根据thmsdnnr的评论,我找出了原因
allInputs[key].replaceWith("<p>" + text+ "</p>") // doesn't work
没有用,因为当使用$(allInputs [key])时,我需要使用$符号。一切正常。
$(allInputs[key]).replaceWith("<p>" + text+ "</p>") //works