简体   繁体   English

MVC部分视图和Javascript

[英]MVC Partial Views and Javascript

I have a partial view which is essentially a widget. 我有一个局部视图,它本质上是一个小部件。 I want to have between 1 and 'n' of these on the same page. 我想在同一页面上包含1到'n'之间的内容。

My issue I'm having is I can't get javascript to execute in each one. 我遇到的问题是我无法在每个脚本中执行javascript。

eg 例如

Index.cshtml Index.cshtml

<div>
   @Html.Partial("_ButtonPartialView")
    <br/>
    <br />
   @Html.Partial("_ButtonPartialView")
</div>

_ButtonPartialView.cshtml _ButtonPartialView.cshtml

<h2>ButtonView</h2>
<button id="foo">
    on
</button>

BundleConfig.cs BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/test").Include(
                        "~/Scripts/test.js"));

Layout.cshtml Layout.cshtml

@Scripts.Render("~/bundles/test")

test.js test.js

$(document).ready(function() {
    $('#foo').click (function() {
        if ($('#foo').html() === 'on') {
            $('#foo').html('off');
        } else {
            $('#foo').html("on");
        }
    });
});

My problem is, when i click the first button it switches between on and off fine. 我的问题是,当我单击第一个按钮时,它会在打开和关闭之间正常切换。 When I click the second button, nothing happens! 当我单击第二个按钮时,什么也没有发生!

My bigger issue, if I can get this to work is. 我更大的问题是,如果我可以解决这个问题。 I obviously want all my Partial Views to be independent. 我显然希望我的所有部分视图都独立。 eg I don't want to click one button and they all trigger. 例如,我不想单击一个按钮,它们都会触发。 They are all going to be passed a model and I need to write JS that will do stuff with that model and display the information. 它们都将传递给模型,我需要编写JS来对该模型进行处理并显示信息。

So each widget needs to be independent. 因此,每个小部件都必须独立。

Thanks 谢谢

As mentioned in the comments, the id must be unique. 如评论中所述,该id必须是唯一的。 If you want to reference the button by id you'll need to generate unique ids. 如果要按ID引用按钮,则需要生成唯一的ID。

A cleaner way is to use a class selector instead with $(this) to reference the button instance that triggered the event. 一种更干净的方法是使用类选择器代替$(this)来引用触发事件的按钮实例。

$(".foo").on("click", function(e) {
    var btn = $(this);
    var state = btn.html();
    ...
});

to trigger script on dynamically added content you need to tie the event to the document. 要在动态添加的内容上触发脚本,您需要将事件绑定到文档。 change your click event to 将您的点击事件更改为

$(document).on('click', '#foo', function() {
    if ($('#foo').html() === 'on') {
        $('#foo').html('off');
    } else {
        $('#foo').html("on");
    }
});

then as mentioned in the other answer change the selector to be partial specific 然后如另一个答案中所述,将选择器更改为部分特定的

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

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