我怕,當我使用的代碼:可以簡化jQuery代碼,讓我變得更加動態
<div id="sentence_xx"></div>
,我總是要打印大量的jQuery代碼。
我可以看到這個鏈接的代碼:
http://jsfiddle.net/hBRNy/2/
問題是,會有人很多
<div id="sentence_xx"></div>
,每次格句我想要打印它,我必須打印整個jquery塊白色它每隔< div>。
有人知道我可以如何解決這個問題嗎?因爲jquery生成的id必須是唯一的,我希望這可以更靈活但不知道如何。
親切的問候
我找到了一個解決方案通過使用jquery通配符(你不能更換ID的被類,因爲ui.jquery不再工作:
<script>
$(document).ready(function() {
// For everey id, started with sentence_ (the sentences which I want)
$('[id^=sentence_]').each(function() {
// strip the id until i have the number only (sentence_ is a static value)
var currentId = $(this).attr('id');
var toRemove = "sentence_";
var id = currentId.replace(toRemove,'');
//replace all the characters by "</li> <li class=\"ui-widget-content_"+id+"\">"
var text = $("#"+currentId).text().trim().split("").join("</li> <li class=\"ui-widget-content_"+id+"\">");
$("#"+currentId).html("<li class=\"ui-widget-content_"+id+"\">" + text + "</li>");
//create a <ol> after the div selectable_xx
$('<ol class="selectable_style" id="selectable_'+id+'"></ol>').insertAfter("#"+currentId);
// remove the value of the div and place them into the <ol>
$('.ui-widget-content_'+id+'').clone().appendTo("#selectable_"+id);
$('#sentence_'+id).remove();
//replace all the " " by non breaking spaces
$('#selectable_'+id+' li').each(function() {
$(this).html($(this).text().replace(' ', ' '));
});
//attache the function for selecting items and put the character place into the next span
$("#selectable_"+id).selectable({
stop: function() {
var woord ="" ;
var result = $("#selectable_"+id).next('span').empty();
$(".ui-selected", this).each(function() {
var index = $("#selectable_"+ id +" li").index(this);
result.append(" #" + (index + 1));
letter = index + 1;
woord += letter+'';
});
}
});
});
});
</script>
如果你想玩它,我已經更新了代碼
http://jsfiddle.net/hBRNy/16/
屬於上:codereview.stackexchange.com –