简体   繁体   English

jQuery:从另一个页面加载变量

[英]jquery: loading variable from another page

Could someone help me with this code? 有人可以帮我这个代码吗?

In my Rails project I have a header that is fixed in position. 在我的Rails项目中,我有一个固定位置的标题。 One of the links is: 链接之一是:

<li><%= link_to "Your Address Book", user_path(current_user), :class => 'random_number' %></li>

Then at the bottom of that same page I have: 然后在同一页面的底部,我有:

  <script>
  var number = 1 + Math.floor(Math.random() * 6);

  $("random_number").click(function("#show_the_number")

           {
             alert(number);
           }
      );

   </script>

The code above doesn't work the way I want it to. 上面的代码无法按照我想要的方式工作。

What I want to happen is: 我想发生的是:

//this part works ok //这部分工作正常

When the 'Your Address Book' link is clicked, load the page 'your address book' and the function 'random_number' 单击“您的通讯录”链接时,请加载页面“您的通讯录”和函数“ random_number”

//here's the problem: //这是问题所在:

When the 'your address book' page loads, there's a button with id '#show_the_number'. 当“您的地址簿”页面加载时,会有一个ID为“ #show_the_number”的按钮。 When this button is clicked on that new page, I want to show the alert(number) message, with the random number from the fixed header. 当在该新页面上单击此按钮时,我想显示警报(数字)消息,其中包含来自固定标题的随机数。

Any ideas? 有任何想法吗? Thanks. 谢谢。

i think what you are asking here is on delegated event..since your button is added dynamically for the click event to work you need to delegate it to its closest static parent 我想你问这里是on委托event..since您的按钮是动态添加click事件工作,你需要将它委托给其最接近的静态父

try this 尝试这个

 $(document).on('click',"#show_the_number",function(){
    var number = 1 + Math.floor(Math.random() * 6);
    alert(number);
});

it is recommended to delegate your event to closest parent container that is present when the page is loaded rather that document itself. 建议将事件委派给加载页面时出现的最接近的父容器,而不是该document本身。

link to read more about .on 链接以了解有关.on更多信息

example: 例:

$("#IdOfParentContainer").on('click',"#show_the_number",function(){
  ....

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

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