简体   繁体   English

将php变量传递给jquery

[英]Passing php variable to jquery

  for($v=0;$v<11;$v++) {
              echo "<div class='unsubscribed'><a class='button'>Unsubscribe</a></div>";
    echo "<div id='$v'></div>";
        }

I want onclick of the class unsubscribed to remove the div below in the same iteration. 我希望取消订阅的类的onclick可以在同一迭代中删除下面的div。 So for this i have to pass $v to jquery. 因此,为此,我必须将$ v传递给jquery。

This is what i started with jquery but i don't know how to get the variable $v. 这是我从jquery开始的内容,但是我不知道如何获取变量$ v。 How do i accomplish this? 我该如何完成?

$.ready(
function() {
$('.unsubscribed').remove();
}
);

you do not need to pass anything to jquery : 您不需要将任何东西传递给jquery:

$(document).ready(function(){
    $('.unsubscribed').one('click',function(){
        $(this).next().remove();
    });
});

This works for your current html. 这适用于您当前的html。
To be more safe, you should add a class to the elements you want to be removed: 为了更安全,您应该在要删除的元素上添加一个类:

 for($v=0;$v<11;$v++) {
     echo "<div class='unsubscribed'><a class='button'>Unsubscribe</a></div>";
     echo "<div class='to_be_removed'></div>";
 }

This way you can reference the div you want to remove withouth it being necessarily after the unsubscribed div : 这样,您可以引用要删除的div,而不必在unsubscribed div之后:

$(document).ready(function(){
    $('.unsubscribed').one('click',function(){
        $(this).next('.to_be_removed').remove();
    });
});

A better solution might be: 更好的解决方案可能是:

<?php for($v=0;$v<11;$v++) { ?>
  <div class="unsubscribed" rel="<?php echo $v; ?>">
     <a class='button'>Unsubscribe</a>
  </div>
  <div id="<?php echo $v; ?>"></div>
<?php } ?>

$(document).ready(function(){
    $(".unsubscribed").click(function(){
        var div_to_remove = $(this).attr("rel");
        $('#'+div_to_remove).remove();
    });
});

I prefer doing it this way, because working with .next can sometimes cause problems, when you add something in between. 我更喜欢这样做,因为在之间添加内容时,使用.next有时可能会导致问题。 It can be very hard to find the problem then. 那时很难找到问题。

This way, you simply embed the needed information about the div you want to remove into an attribute of the div that triggers the event. 这样,您只需将有关要删除的div的所需信息嵌入到触发事件的div属性中。

Note: in this example, the function is called on clicking the .unsubscribed div - not the .button . 注意:在此示例中,该函数是在单击.unsubscribed div而不是.button

You also have to make sure, the removable div s have different and unique ids. 您还必须确保可移动div具有不同且唯一的ID。 If $v isn't unique, you can do eg something like this: 如果$v不是唯一的,则可以执行以下操作:

...
<div id="<?php echo $v . $i; ?>"></div>
...

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

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