繁体   English   中英

jQuery PHP在函数内传递值与实时点击?

[英]jQuery PHP passing values within functions vs live clicking?

我试图通过onclick传递一些值,这对我来说要快得多。 但我需要使用某种“实时”点击,我正在研究.on()或.delegate()。 但是,如果我执行其中任何一项,那么在followme()传递这些值似乎有点难以获得。 我有没有看到某种方法?

    <div class='btn btn-mini follow-btn' 
         data-status='follow' 
         onclick="followme(<?php echo $_SESSION['user_auth'].','.$randId;?>)">
            Follow 
    </div>

function followme(iduser_follower,iduser_following)
{

        $.ajax({
        url: '../follow.php',
        type: 'post',
        data: 'iduser_follower='+iduser_follower+'&iduser_following='+iduser_following+'&unfollow=1',
        success: function(data){
                $('.follow-btn').attr("data-status",'follow');
                $('.follow-btn').text('Follow');
            }

        });

}

正如您所看到的,更容易将值从PHP传递到jQuery ...还有另一种方法吗?

您可以分配更多数据值,并且知道登录的用途,您只需传递要关注的人:

<div class='btn btn-mini follow-btn' 
     data-status='follow' 
     data-who='<?php echo $randId; ?>'
     id='followBTN'>
        Follow 
</div>

<script>
    $('#followBTN').on('click', function(){
        $.ajax({
            url: '../follow.php',
            type: 'post',
            data: {
                iduser_following: $(this).attr('data-who')
            },
            success: function(data){
                $('.follow-btn').attr("data-status",'follow');
                $('.follow-btn').text(data.text);
            }

        });
    });
</script>

你可以直接从PHP处理$_SESSION['user_auth']和状态,你不需要在jQuery中传递它们。 确保document当您插入准备on单击事件。

只需使用jquery'on'事件。 将一个名为data-session的新属性附加到div,然后使用.attr方法检索它。 您可以通过下面的示例向您显示包含数据的警报,您只需将其替换为您的代码即可

<html>
<head>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
   <script>
      $(document).ready(function(){
         $(document).on('click', '#follow-me-button', function(){
            alert($(this).attr('data-session'));
         })
      })
   </script>
</head>
<body>
   <div id="follow-me-button" class='btn btn-mini follow-btn' data-status='follow' data-session ="MY-SESSION-DATA-FROM-PHP">
            Follow
    </div>
</body>
</html>

暂无
暂无

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

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