所以我有3篇来自当地报纸的文章我希望用户点击一个按钮和页面切换的内容,我第一次点击任何按钮时写了我的脚本它会为我切换内容但是当点击时之后的任何按钮都没有结果 我的src代码类似于
<div id="banner">
<div id="nav">
<ul>
<li><button onclick="one()">one</button></li>
<li><button onclick="two()">two</button></li>
</ul>
</div>
<div id="thewholetext">
<p id="a">
//an article here
<p id="b">
// a 2nd article here
</div>
</div>
,java脚本就像
function one () {
document.getElementById("thewholetext").innerHTML = a.innerHTML;
}
function two() {
document.getElementById("thewholetext").innerHTML = b.innerHTML;
}
这个想法是我有一个名为“全文”的div,其中包含两篇文章,每篇文章都有唯一的ID,所以当用户点击相应的按钮时我只能控制和显示其中一个 我希望它清楚。提前谢谢
答案 0 :(得分:0)
尝试声明你的功能
$("button").click(function(e) {
if (e.target.id == "one") {
$("#a").show();
$("#b").hide();
} else {
$("#a").hide();
$("#b").show();
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav">
<ul>
<li>
<button id="one">one </button>
</li>
<li>
<button id="two">two </button>
</li>
</ul>
</div>
<div id="thewholetext">
<p id="a" style="display:none;">
//an article here
</p>
<p id="b" style="display:none;">
// a 2nd article here
</p>
</div>
&#13;
希望有所帮助:)
答案 1 :(得分:0)
// Cache buttons and articles
var buttons = document.querySelectorAll("[data-showid]"),
allArticles = document.querySelectorAll(".article");
function toggleArticle(event) {
event.preventDefault(); // Prevent document scrollTop
var id = this.dataset.showid,
article = document.getElementById( id );
[].forEach.call(allArticles, function( art ) {
art.style.display = art === article ? "block" : "none";
});
}
// Button clicks
[].forEach.call(buttons, function( btn ) {
btn.addEventListener("click", toggleArticle, false);
});
&#13;
.hidden{display:none;}
[data-showid]{ color:red; cursor:pointer; }
&#13;
<a data-showid="article1">One</a>
<a data-showid="article2">Two</a>
<p id="article1" class="article">This is article ONE</p>
<p id="article2" class="article hidden">This is article TWO</p>
&#13;
答案 2 :(得分:0)
<html>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
<style>
p{
display:none;
}
</style>
<script>
$(document).ready(function(){
$("button").on("click",function(e){
$("p").hide();
$("p#"+this.id).show();
});
});
</script>
<body>
<div id="nav">
<ul>
<li><button id="one">one </button> </li>
<li><button id="two">two </button> </li>
</ul>
</div>
<div id="thewholetext">
<p id="one">
//an article here
</p>
<p id="two">
// a 2nd article here
</p>
</div>
</div>
</body>
</html>