我有一个包含两个输入字段和一个标签云的表单。
我希望用户将焦点放在第一个输入中,然后单击一个标记,从而触发一个jquery函数,将单击的标记放在第一个输入中。然后用户聚焦第二个输入,单击触发类似jquery函数的标记,将第二个标记放在第二个输入字段中。
我的代码用于将第一个标记放在第一个输入中,但是当单击第二个标记时,该单击标记将被放入两个输入字段中。
我怀疑我需要帮助$(this).html或绑定。我很清楚,$('a')。click函数发生了两次,最新值为$(this).html()。
如何隔离这两个函数,以便第一个标记写入第一个输入,第二个标记只写入第二个输入?
以下是我编写html和jquery的方法:
表格:
<div id="content">
<h3 class="replaceTag">Replace A Tag</h3>
<p class="showToReplace">Replace
<input class="inputToReplace" type="text" name="" value="">
With
<input class="inputWithReplace" type="text" name="" value="">
<input type="button" name="" value="Go">
</p>
标签云的结构,为简洁起见仅显示“A”。
<div id="tagReference">
<div class="tagWindow">
<h4 class="alphaLetter">A</h4>
<div id="alphachunk">
<a class="_tag_suggestion">access, </a>
<a class="_tag_suggestion">accessibility,</a>
<a class="_tag_suggestion">accountant, </a>
<a class="_tag_suggestion">acoustical,</a>
</div>
<h4 class="alphaLetter>B</h4>
<div id="alphachunk">
<!--and so on for the alphabet-->
</div>
</div>
</div>
对于标签所存在的每个字母都会出现这种情况。
这是jQuery
$(document).ready(function(){
$('.inputToReplace').focus(function(){
$("a").click(function(){
$('.inputToReplace').val($(this).html());
});
});
$('.inputWithReplace').focus(function(){
$("a").click(function(){
$('.inputWithReplace').val($(this).html());
});
});
});
现在,一个可爱的屏幕截图。 alt text http://www.kevtrout.com/stackoverflowimages/editTagsScrn.png
答案 0 :(得分:0)
jQuery允许您绑定多个单击事件处理程序。在添加第二个之前,您将需要使用.unbind
解除绑定前一个点击事件处理程序(或者两个都将触发,如您所见):
$("a").unbind("click");
所以你的代码可以读取:
$('.inputWithReplace').focus(function(){
$("a").unbind("click").click(function(){
$('.inputWithReplace').val($(this).html());
});
});
答案 1 :(得分:0)
您可以将代码缩短为
$(document).ready(function(){
$('input:text').focus(function(e){
tagSelector(e.target);
});
});
function tagSelector(elem) {
$("a").unbind('click').click(function(e){
$(elem).val($(e.target).text());
});
}
您可能需要为输入使用更具体的选择器,我会将其作为练习让您自行决定:)
修改强>
甚至是
$(function(){
$('input:text').focus(tagSelector);
});
function tagSelector(e) {
$("a").unbind('click').click(function(){
$(e.target).val($(this).text());
});
}