在Javascript中使用动态创建的对象的CRUD操作 [英] CRUD operations using dynamically created objects in Javascript

查看:35
本文介绍了在Javascript中使用动态创建的对象的CRUD操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用JavaScript进行基本的Crud操作,我遇到了一些困难。让我通过向您展示代码来解释:



I am trying to do basic Crud operation in JavaScript and I am having some difficulty. Let me explain by showing you the code:

<html>
    <head>
        <title></title>
    </head>
<body>
    <input id="name" type="text" value="" />
    <input id="Add" type="button" value="Add" />
   
    <div id="userList" ></div>

<script type="text/javascript" src="../Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
    $(function ($) {
        var User = function (name) {
            this.Name = name;
            this.Delete = function () {
                // this will be button element
                alert(this.Name);
                // how can I access the user element here ?
            }
        }

        $('#Add').click(function () {
            nUser = new User($('#name').val());
            $('#userList').append(GetViewTemplate(nUser));
        });

        function GetViewTemplate(user) {
            var del = $("<input type='button' value='Delete' />");
            // I am binding the click event of an instance method
            del.click(user.Delete);

            var li = $("<div>" + user.Name + "</div>");
            li.append(del);
            li.append("<br />");

            return li;
        }

    });
</script>
 
</body>
</html>





我有一个JavaScript中的User类,其属性为Name,函数为Delete。



单击添加按钮时:

我正在创建一个用户对象并为Name属性分配文本框值





I have a "User" class in JavaScript, which has a property "Name" and a Function "Delete".

When the Add button is clicked:
I am creating a user object and assigning text box value to Name property

var nUser = new User($('#name').val());





我正在显示新的我在DIV中创建了用户显示名称和删除(动态创建)按钮,为用户分配相同的onclick功能(obj)删除功能





I am displaying the newly created user in a DIV where I am showing the Name and a "Delete" (created dynamically) button assigning the onclick function of the same to the user (obj) "Delete" function

var del = $("<input type='button' value='Delete' />");
del.click(user.Delete);





但是当点击删除按钮时我想访问用户实例而不是按钮元素。



有什么方法可以实现这个目的吗?



But when the "Delete" button is clicked I want to access the User instance and not the button element.

Is there any way to accomplish this ?

推荐答案

function


){
var User = function (name){
this .Name = name;
.Delete = function (){
// 这将是按钮元素
alert( this .Name);
// 如何在此处访问用户元素?
}
}
) { var User = function (name) { this.Name = name; this.Delete = function () { // this will be button element alert(this.Name); // how can I access the user element here ? } }


' #Add')。点击(< span class =code-keyword> function (){
nUser = new 用户(
('#Add').click(function () { nUser = new User(


这篇关于在Javascript中使用动态创建的对象的CRUD操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆