简体   繁体   English

无法在mvc4中使用onclick从定位标记获取呼叫

[英]unable to get call from anchor tag using onclick in mvc4

cshtml code cshtml代码

<div class="span3">
    @for (var i = 0; i < Model.GroupNames.Count; i++)
    {
        <ul>                 
            <li>
                @{
                    var item = Model.GroupTypeNames[i];
                    var selected = i == 0 ? " class=\"selected\"" : "";
                }

                <a onclick="getGroupType(@item.Id);" data-option-value="*"@Html.Raw(selected)>@item.TypeName</a>
            </li>
        </ul>
    }
</div>

jquery code jQuery代码

function getGroupType(id) {
    debugger;
    $.getJSON( "Groups/Get" + id, function (data) {
        $(".span9").html($("#GroupTemplate").removeData());
        $.each(data, function (index, value) {
            if (value.Id != undefined) {
                $("#GroupTemplate").tmpl(value).appendTo(".span9");
            }
        });

        $('#circle').css("opacity", "0.5");
    });
}

Unable to get call here but when I try to use onclick="alert('Hello');" 无法在这里打电话,但是当我尝试使用onclick="alert('Hello');" it is working perfectly 它工作正常

what wrong with onclick="getGroupType(@item.Id);" onclick="getGroupType(@item.Id);"

I would expect you get the error: 我希望你会得到错误:

ReferenceError: getGroupType is not defined ReferenceError:未定义getGroupType

Because I suspect that your JavaScript code appears later in the file than your onclick attribute. 因为我怀疑您的JavaScript代码出现在文件中的位置比您的onclick属性晚。

When using attributes, make sure the function is defined before the attributes... usually in the <head> . 使用属性时,请确保在属性之前定义函数...通常在<head> Having said this, normal practice is to include scripts later and attach the events in the script, rather than using attributes. 话虽如此,通常的做法是稍后包括脚本并将事件附加到脚本中,而不是使用属性。

Also, make sure your function isn't wrapped inside another function. 另外,请确保您的函数未包装在另一个函数中。 JavaScript is functionally scoped, and a function wrapped in another function won't be callable from global scope. JavaScript在功能上是作用域的,并且包装在另一个函数中的一个函数将无法从全局范围调用。

This all assumes id is actually a number. 所有这些都假定id实际上是一个数字。 If the id is a string, remember to wrap it in quotes too. 如果id是字符串,请记住也将其用引号引起来。 GUIDs must be treated like strings in JavaScript... GUID必须像JavaScript中的字符串一样对待...

onclick="getGroupType('@item.Id');"

As you commented: 如您所言:

my function is in ready 我的功能已准备就绪

so i think here is a scoping issue, because your onclick handler is not in the ready function so your function getGroupType(@item.Id); 所以我认为这是一个范围问题,因为您的onclick处理程序不在ready函数中,因此您的函数getGroupType(@item.Id); is not available for it, instead you can put it outside in the gloabal scope. 无法使用它,而是可以将其放置在全球范围之外。

getGroupType(id){
  // all the stuff
}

$(function(){
   // all other stuff
});

您将需要用单引号将参数包装起来。

onclick="getGroupType('@item.Id');" 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM