简体   繁体   English

jQuery:根据更改的变量值更改div文本

[英]jQuery: change div text depending on changing variable value

I need to create a donations page for a website. 我需要为网站创建一个捐赠页面。 Basically I want the user to use a slider bar to select the amount they wish to donate. 基本上,我希望用户使用滑块来选择他们希望捐赠的金额。 I have used the following tutorial to create a basic slider bar - http://designm.ag/tutorials/howto-build-range-slider-input-with-jqueryui/ . 我已使用以下教程来创建基本的滑块-http: //designm.ag/tutorials/howto-build-range-slider-input-with-jqueryui/

<div id="defaultval">
    Slider Value: <span id="currentval">0</span>
</div>
<div id="defaultslide"></div>

The above code is taken from the tutorial and displays the slider bar. 上面的代码取自教程,并显示滑块。 The value in the span tag 'currentval' changes as the user changes the place of the slider, as seen in the live demo of the tutorial http://designm.ag/previews/jqueryui-range-sliders/ 当用户更改滑块的位置时,span标记“ currentval”中的值会更改,如教程http://designm.ag/previews/jqueryui-range-sliders/的实时演示中所示

The jQuery used for the slider bar is as follows: 滑块使用的jQuery如下:

<script>
$(function(){
  $('#defaultslide').slider({ 
    max: 250,
    min: 0,
    value: 0,
    slide: function(e,ui) {
      $('#currentval').html(ui.value);
    }
  });
</script>

I then have a div below where I wish to display text describing a different perk depending on the value of the slider bar. 然后,在下面有一个div,我希望在其中显示根据滑块的值描述不同特权的文本。 Eg if the slider bar value > 100 display perk 1, slider bar value > 200 display perk 2 etc... 例如,如果滑杆值> 100显示权限1,滑杆值> 200显示权限2等...

<div id="perk">
   <span>"Perk number..."</span>
</div>

I've had a play around trying to do this but I've had no luck, the only way I can think of doing it is as follows: 我一直在尝试这样做,但是我没有运气,我想到的唯一方法如下:

if($value > 100) {
    $('#perk span').text('Perk number 1');
}

Obviously this is incorrect. 显然这是不正确的。 How would I do this using jQuery? 我将如何使用jQuery做到这一点?

What the value in the variable $value contains is not clear from the code you provided. 您提供的代码尚不清楚变量$value包含的$value

You should be attempting to find the val() or .value from the slider itself. 您应该尝试从滑块本身中找到val().value

Edit: I found the solution! 编辑:我找到了解决方案! From looking at the source code of the tutorial, I found that the value of the slider is stored in a variable called ui.value within the scope of slide: function(e,ui) . 通过查看本教程的源代码,我发现滑块的值存储在slide: function(e,ui)范围内的名为ui.value的变量中。 Simply call that, as in: 只需调用它即可,如:

if(ui.value > 100) {
    $('#perk span').text('Perk number 1');
}

do it within the slide function, like as follows: 在slide函数中进行操作,如下所示:

  $('#defaultslide').slider({ 
    max: 1000,
    min: 0,
    value: 500,
    slide: function(e,ui) {
      if(ui.value > 100) {
       $('#perk span').text('Perk number 1');
     };
    }
  });

Hope that helped. 希望能有所帮助。

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

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