JQuery动态更改html内容

时间:2015-07-07 03:11:29

标签: javascript jquery html css

我有一个右侧边栏,可以滑出并显示内容。侧边栏可以从多个按钮(button1,button2,button3等)打开。单击某些按钮时,侧边栏中的内容需要不同?最有效的方法是什么?我尝试使用.html()但它会覆盖样式。例如,如果button1触发的内容为“Test”且button2显示“Test2”,如果再次单击button1,则显示“Test2”。有没有办法有效地保持每次点击事件的数据一致性?

2 个答案:

答案 0 :(得分:0)

试试这段代码:

$("input").click(function() {
  var value = this.getAttribute('data-dynamicContent');
  document.getElementById('dynamicContent').innerHTML = value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" data-dynamicContent="This is your content" value="button one">
<input type="button" data-dynamicContent="This is your content 2" value="button two">
<input type="button" data-dynamicContent="This is your content 3" value="button three">
<div id="dynamicContent"></div>

这是一个不那么干净但提供更好的浏览器支持的产品:

$('input').click(function() {
  document.getElementById('dynamicContent').innerHTML = this.name;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" name="your content one" value="button one">
<input type="button" name="your content two" value="button two">
<input type="button" name="your content three" value="button three">
<div id="dynamicContent"></div>

这是一个拥有更多代码但拥有最佳浏览器支持的代码:

$('input').click(function() {
  document.getElementById('dynamicContent').innerHTML = this.nextElementSibling.value;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="button" value="button one">
  <input type="hidden" value="your content one">
</div>

<div>
  <input type="button" value="button two">
  <input type="hidden" value="your content two">
</div>

<div>
  <input type="button" value="button two">
  <input type="hidden" value="your content three">
</div>

<div id="dynamicContent"></div>

答案 1 :(得分:0)

请参阅此示例:http://jsfiddle.net/kevalbhatt18/2mmvjf9c/

$('button').click(function(){
   console.log($(this)[0].innerText)
    if($(this)[0].innerText === "button 1"){
      $('span').html('test 1')
    } else  if($(this)[0].innerText === "button 2"){
      $('span').html('test 2')
    }else{
    $('span').html('test 3')
    }
})