我有一个简单的 html 菜单,当一个菜单项被点击时,一个类 `mg_cats_selected"被添加到 anchor 标签(这是菜单项)。
我想复制事件/选定 anchor 标记的文本值并将其显示在页面上的另一个 div 中,但我只想显示一次。单击新元素链接时,我想从我创建它的单独 div 中删除旧值并显示新选定菜单项的新值。
我希望这是有道理的。
这是 HTML 菜单
<div id="mgf_165" class="mg_filter mg_new_filters">
<a rel="163" id="163" class="mgf_id_163 mgf mg_cats_selected left_menu" href="javascript:void(0)">Bathrooms Sinks</a>
<a id="164" rel="164" class="mgf_id_164 mgf left_menu" href="javascript:void(0)">Bowed</a>
</div>
这是我要显示文本值的 jQuery 和 div。
<script type="text/javascript">
jQuery(document).ready(function(){
console.log('test');
jQuery("a.left_menu").click(function(){
var txt = jQuery("a.left_menu").text();
//$(this).attr('rel');
jQuery("#category").append(txt);
});
});
</script>
<div id="category">
</div>
当我点击“鞠躬”时,它会显示在 div 中
Bathrooms SinksBowed
如果我再次点击“Bathroom Sinks”,同样的事情会重复
Bathrooms SinksBowedBathrooms SinksBowed
我该如何处理?我在这里遵循了正确的逻辑吗?
最佳答案
您目前正在获取所有菜单项的文本,然后将其附加到 div
。
需要获取被点击的菜单项的文本,然后将div
的内容设置为该菜单项的文本值。
jQuery(this) // the clicked menu item
jQuery('#category').text('VALUE') // set the text content of the tag to VALUE
Working solution on JSFiddle. .
参见 Inside the Event Handling Function了解有关 jQuery
事件处理的更多信息。
关于javascript - 使用 jQuery 在 div 中显示选定/事件链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34623949/