我正打算创建一个基本的jquery插件(用于教育和自学习目的),我只想在每次通过jquery调用函数时将select元素转换为div元素,例如$('。anyID')。newdiv() ;
所以这就是它应该如何
来自:
<select id="anyID"><option value="">Default Text</option>
<option value="one">First</option>
<option value="two">Second</option>
<option value="three">Third</option>
<option value="four">Fourth</option>
<option value="five">Fifth</option>
</select>
进入这个:
<div class="random class" id="anyID">
<div class="default text">Default Text</div>
<div class="content">
<div class="item" data-value="one">First</div>
<div class="item" data-value="two">Second</div>
<div class="item" data-value="three">Third</div>
<div class="item" data-value="four">Fourth</div>
<div class="item" data-value="five">Fifth</div>
</div>
</div>
这可能吗? 任何帮助都会非常感激 谢谢你们:))
答案 0 :(得分:1)
试试这个
var html=''
var firstOption='';
var remainingOptions='<div class="content">';
$('#anyID option').each(function(index,item){
if(index>0){
remainingOptions+='<div class="default text">'+$(item).text()+'</div>'
}
else
{
firstOption+='<div class="item" data-value="'+$(item).val()+'">'+$(item).text()+'</div>'
}
})
html+=firstOption;
html+=remainingOptions;
html+='</div></div>'
$('#datadiv').html(html)
答案 1 :(得分:0)
这是可能的。该功能看起来像这样
function(anyID){
let $selectElem = $(`#${anyID}`),
$options = $selectElem.find('options'),
$firstOption = $options.splice(0,1),
$div = $('<div></div>'),
$contentDiv = $div.clone().addClass('content'),
$containerDiv = $div.clone().attr('id', anyID),
$firstDiv = createDivFromOption($firstOption).addClass('default text');
$containerDiv.append( $firstDiv )
.append( $contentDiv );
$options.each(index => {
let $option = $(this);
createDivFromOption($option).appendTo($contentDiv);
});
function createDivFromOption($option){
let value = $option.attr('value'),
text = $option.html();
return $div.clone()
.addClass('item')
.attr('data-value', value)
.html(text);
}
}