我正在努力将我在网上找到的链式下拉功能改编到我的网站上。我在网上找到的一些代码如下。一个问题是我无法理解读取var connection = selected.data('connection');
连接属性是 jquery 共有的行吗?还是在代码中的某个位置设置?如果是这样,这组在代码中的什么位置?
$(function(){
var questions = $('#questions');
function refreshSelects(){
var selects = questions.find('select');
// Improve the selects with the Chose plugin
selects.chosen();
// Listen for changes
selects.unbind('change').bind('change',function(){
// The selected option
var selected = $(this).find('option').eq(this.selectedIndex);
// Look up the data-connection attribute
var connection = selected.data('connection');
// Removing the li containers that follow (if any)
selected.closest('#questions li').nextAll().remove();
if(connection){
fetchSelect(connection);
}
});
}
var working = false;
function fetchSelect(val){
if(working){
return false;
}
working = true;
$.getJSON('ajax.php',{key:val},function(r){
var connection, options = '';
$.each(r.items,function(k,v){
connection = '';
if(v){
connection = 'data-connection="'+v+'"';
}
options+= '<option value="'+k+'" '+connection+'>'+k+'</option>';
});
if(r.defaultText){
// The chose plugin requires that we add an empty option
// element if we want to display a "Please choose" text
options = '<option></option>'+options;
}
// Building the markup for the select section
$('<li>
<p>'+r.title+'</p>
<select data-placeholder="'+r.defaultText+'">
'+ options +'
</select>
<span class="divider"></span>
</li>').appendTo(questions);
refreshSelects();
working = false;
});
}
$('#preloader').ajaxStart(function(){
$(this).show();
}).ajaxStop(function(){
$(this).hide();
});
// Initially load the product select
fetchSelect('productSelect');
});
看看 jQuery.data() 函数。此函数允许您存储和检索与指定元素关联的任意数据。
在您的示例中,"选项"具有名称连接的某些属性。查看代码,似乎属性连接用于决定在链中选择下一个链接中的哪个。