jQuery上下文菜单获取被点击的项目

时间:2011-01-18 15:41:10

标签: javascript jquery jquery-selectors contextmenu

我正在使用jQuery context menu plugin by Chris Domigan来应用上下文菜单。我就是这样做的:

$('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
        'copy': function(t) {
             alert('Trigger was '+t.id+'\nAction was Copy');
         },

        'delete': function(t) {
             alert('Trigger was '+t.id+'\nAction was Delete');
        }
    },             
});

我的问题是,如何获取所点击的tr项目的内容?我试过

$(t.target).html()

但它会返回null。有什么想法吗?

编辑:这里是示例http://jsfiddle.net/gqhRV/

2 个答案:

答案 0 :(得分:9)

我认为这就是你想要的:

<script type="text/javascript"> 
$(function(){
$.contextMenu({
    selector: '.flexme1 tbody tr', 
    callback: function(key, options) {
        alert("Clicked on " + key + " on element " + options.$trigger.attr('id').substr(3));            
    },
    items: {
        "edit": {name: "Edit", icon: "edit"},
        "cut": {name: "Cut", icon: "cut"},
        "copy": {name: "Copy", icon: "copy"},
        "paste": {name: "Paste", icon: "paste"},
        "delete": {name: "Delete", icon: "delete"},
        "sep1": "---------",
        "quit": {name: "Quit", icon: "quit"}
    }
});

$('.flexme1 tbody tr').on('click', function(e){
    console.log('clicked', this);
})
});
</script>

它与Flexigrid集成......对我来说很好......

显然我有一些额外的选择。

答案 1 :(得分:7)

不熟悉插件,但从它的外观来看,你应该可以写:

$("#" + t.id).html();

但是对于大多数jQuery插件,你应该能够这样做:

$(this).html();

来自'copy': function(t) {'delete': function(t) {

的上下文
$('#contacts tbody tr').contextMenu('myMenu1', {
    bindings: {
        'open': function(t) { ShowAction(t, "Open"); },
        'email': function(t) { ShowAction(t, "Email"); },
        'save': function(t) { ShowAction(t, "Save"); },
        'delete': function(t) { ShowAction(t, "Delete"); }
    }
});

function ShowAction(t, a) {
    alert('Trigger was ' + t.id + '\nAction was ' + a + "\nHtml is " + $(t).html());
}

以下是一个有效的例子:http://jsfiddle.net/dNUgg/

我猜你的<tr>代码没有id属性


即使<tr>没有ID,这仍然有效:http://jsfiddle.net/dNUgg/1/


 alert('content is ' + $(t).text() + '\nAction was Delete');

更新了你的jsfiddle:http://jsfiddle.net/gqhRV/1/

当你应该做$(t.target).text()

时,你正在做$(t).text()