检查点击了什么然后是条件,如果没有,那么条件

时间:2015-05-21 03:36:20

标签: javascript jquery

我想根据点击的按钮加载视图。当然,当第一次登陆页面加载时没有点击任何内容,它将加载特定的视图。但是当用户单击其中一个按钮时,第一个视图将根据所点击的内容被视图替换。

这是我一直在尝试的。

$(".pagesbutton").click(function(){
    $(this).data('clicked', true);

    if($('.pagesbutton').data('clicked')) {
      buttonpressed = $(this).attr('id');
      if(buttonpressed == 'one') {
        //will load the view of one
      }
      else {
        //will load the view of two
      }
    }


    else {
        //will load the view of default
        //it is the first land of the page load when nothing is clicked. 
    }
});

第一次加载页面时,jquery仅警告default视图。但在那之后,当我点击所有按钮时,它不会发出任何警报。

3 个答案:

答案 0 :(得分:2)

DEMO - JS Fiddle

我认为你的JQuery应该是这样的:

$(document).ready(function() {
   $('.theView').prepend('The default view!');
});

$('.pagesbutton').on('click', function() {
   $('.theView').empty();
   var buttonpressed = $(this).attr('id');
   if (buttonpressed == 'one') {
      $('.theView').prepend('The view of One!');
   }
   else {
      $('.theView').prepend('The view of Two!');
   }
});

<div class="theView">this is one view bla bla bla with css class and id</div>

答案 1 :(得分:1)

您希望绑定到元素的click事件,然后使用属性数据获取页面并将其加载到元素中:

[注意 - 请参阅代码示例注释以获取更多观察结果]

&#13;
&#13;
// bind to class link event
// this will fire when a '.link' element is clicked.. not just div
// open console to see logs

$('.link').click(function() {

  // this = element clicked
  console.log($(this));

  // get data-* attribute value
  var pageRef = $(this).attr('data-page');
  console.log(pageRef);

  // [Note] jQuery.data() is not the same as data attribute
  // attr = DOM, data = javascript object
  // example:
  console.log($(this).data('page'));
  // same as pageRef
  // but..
  $(this).data('page', 'nonsense');
  console.log($(this).data('page')); // nonsense
  console.log($(this).attr('data-page')); // foo

  // just be consistent with attr - data
  // load the page?
  loadPage(pageRef);

});

// helper!
function loadPage(ref) {
  $('#loader').empty(); // removes everything there before
  // load the page:
  //$('#loader').load("/" + ref);
  $('#loader').html(ref);
}
&#13;
div{
    display : inline-block;
    border: dashed 2px steelblue;
    height: 100px;
    width: 100px;
}

.link{
    cursor: pointer;
}
#loader{
  display : inline-block;
  border: solid 2px pink;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="link" data-page="foo"><a href="#">foo</a>
</div>
<div class="link" data-page="bar"><a href="#">bar</a>
</div>
<div class="link" data-page="baz"><a href="#">baz</a>
</div>
<div id="loader">Loading data...</div>
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

这是你可能想要的东西:

$(".pagesbutton").click(function(){
    // replace the view, you might want something like this
    $('#some_div').text('clicked by pagesbutton');
});

$(".otherbutton").click(function(){
    $('#some_div').text('clicked by otherbutton');
});