代码之家  ›  专栏  ›  技术社区  ›  rg88

用Javascript在动态生成的链接中传递数据

  •  1
  • rg88  · 技术社区  · 15 年前

    问题是: 下面是我如何用js传递数据。这是一个好办法还是我做错了?它确实管用,但似乎。。。我想,对我的技术有点怀疑。

    我想能够点击“编辑”链接,在每一行弹出一个模式窗口来管理数据。可能会更改用户的角色。

    网格由封装在匿名函数中的代码生成,模式由封装在不同匿名函数中的代码生成。我需要为特定的点击行填充正确的数据。

    <a href="#" userrole="role1" userid="12345"> Manage </a>

    因此,单击该链接将启动模态窗口,然后我使用一些jquery获取属性值并填充模态。举个例子:

    首先,处理click的代码(假设click处理程序和其他document.ready()内容被分配了。。。为了简洁起见,我省略了这一点,但这是基于正确工作的代码):

    (function(){
        var EditUserClick = function(e) {
            userRole = $(this).attr('userrole'); //assign some values
            userId = $(this).attr('userid'); // assign some values
    
            OpenEditUserModal(userRole,userId); 
        }
    });
    

    第二,处理模态的代码:

    //Public stuff so it's accessible to the click.
    var OpenEditUserModal;
    
    (function(){
        OpenEditUserModal = function(userRole,userId){
            //code to handle the modal window opening can go here
            //populate the modal
            $('#userRole').text(userRole); // let's say this is a text field
            $('#userId').val(userId); //let's say this is a hidden form field
        }
    });
    

    那怎么样?有没有比将数据分配给组合的链接属性并将其一次单击传递给下一个方法更好的方法来传递这些数据?欢迎任何其他建议。。。总是在学习。

    1 回复  |  直到 15 年前
        1
  •  1
  •   Community CDub    8 年前

    如果你不关心你的HTML文档是否通过了验证检查,代码是否能正常工作,那就这样吧。

    作为一种较少干扰、更符合标准的方法,您可以将所有的东西都放到 href公司 属性,只需在单击时解析键值对( see this question

    <ul>
    <li><a href="index.html?foo=bar&id=1">first</a>/li>
    <li><a href="?foo=woo&id=2">second</a></li>
    </ul>
    

    这方面的琐碎JS:

    $('a').click(function(){
        var querystring = $(this).attr('search');
        //console.log(querystring);
    
        // parse here and call OpenEditUserModal       
        return false;
    });