(一)html代码结构
<div style="float:left;" class="tags_leftz">
<input type='text' name='tags' id="tags" value='' style='width: 420px;' class='input-text' >
<div id="selectedTagsDiv">
<div class="tag_sytle">
<?php
if(isset($keyword_tag)){
foreach($keyword_tag as $key=>$val){
echo "<div>";
echo '<input type="hidden" name="selectedTags[]" value="'.$val['tag'].'">';
echo '<span οnclick="javascript:removeTag(this)">'.$val['tag'].'</span>';
echo "</div>";
}
}
?>
</div>
</div>
<ul id="search_div" style="position:relative; left:0;"></ul>
</div>
(二)js代码
//键盘按键事件
$(function(){
$('#tags').keyup(function(){
var value = $("#tags").val();
if (value.length > 0){
$.getJSON(
'?m=jx&c=index&a=public_tag_search',
{tag: value},
function(data){
if (data != null) {
var str = '<li style="position:absolute; right:10px; top:0px; text-align:right; font-size:18px; cursor: pointer;" οnclick="close1()">x</li>';
$.each(data, function(i,n){
str += '<li style="padding-left:4px;" οnclick="input_tag(this)">'+n.tag+'</li>';
});
$('#search_div').html(str);
$('#search_div').show();
} else {
$('#search_div').hide();
}
});
} else {
$('#search_div').hide();
}
});
});
//把目标关键词追加到指定位置
function input_tag(obj){
var tag = jQuery.trim($(obj).text());
var isExists = false;
jQuery('#selectedTagsDiv').find("span").each(function(){
if(jQuery.trim(jQuery(this).text())==tag){
isExists = true;
}
});
if(!isExists){
var pHtml = "<div><div style='float:left;margin-right:15px;' ><input type='hidden' name='selectedTags[]' value='"+tag+"'>";
pHtml+="<span οnclick='javascript:removeTag(this)'>"+tag+"</span></div></div>";
jQuery('#selectedTagsDiv').append(pHtml);
jQuery('#selectedTags').val("");
}
}
//移除已经选定的关键词
function removeTag(pObj){
var pTag = jQuery.trim(jQuery(pObj).text());
jQuery("input[name='selectedTags[]']").each(function(){
if(jQuery(this).val()==pTag){
jQuery(this).remove();
}
});
pObj.remove();
}