我正在尝试构建一个菜单,我希望根据我按下的按钮进行动态定位。
所以例如,我的jquery代码看起来像这样
jQuery(function($) {
$("button").on("click", function() {
$('.nav-content').find('> .nav-links').addClass("hidden");
$('#students').removeClass("hidden");
});
});
但我想知道我是否能写出类似的东西
$('#'.'(this).attr(data-content)').addClass("hidden");
这是qazxsw点的链接,可以查看代码的完整上下文
正确的语法是
JSFiddle
以下是var currentId = $(this).attr('data-content');
$('#'+currentId).addClass("hidden");
中代码的更新版本,其中包含解决方案:js代码注释中的说明。
jsfiddle
jQuery(function($) {
var $nav = $('.nav-content'); // nav parent
var targets = $nav.find('.nav-links') // links (targets)
$("button").on("click", function() {
var $button = $(this);
var targetId = '#'+$button.data('content') // get the id of the target
var $target = $nav.find(targetId); // find the target
targets.addClass("hidden"); // hide all targets
$target.removeClass("hidden"); // show target with the specific id
});
});
.main-container {}
.nav-buttons {
background-color: blue;
}
.nav-buttons button {}
.nav-content {
background-color: red;
height: auto;
max-height: 70vh;
overflow: hidden;
}
.content-1 {}
.content-2 {}
.content-3 {}
.shown {
display: block;
opacity: 1;
}
.hidden {
display: none;
opacity: 0;
}
使用JS中的<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<div class="main-container">
<div class="nav-buttons">
<button data-content="home">Home</button>
<button data-content="brands">Brands</button>
<button data-content="students">Students</button>
</div>
<div class="nav-content">
<div data-content="brands" id="brands" class="nav-links">
<p>this is a brand</p>
<p>this is a brand</p>
<p>this is a brand</p>
<p>this is a brand</p>
<p>this is a brand</p>
</div>
<div data-content="students" id="students" class="nav-links hidden">
<p>this is a student</p>
<p>this is a student</p>
<p>this is a student</p>
<p>this is a student</p>
<p>this is a student</p>
<p>this is a student</p>
<p>this is a student</p>
<p>this is a student</p>
</div>
<div class="static-nav-links">
<p>this link shall always be here</p>
<p>this link shall always be here</p>
</div>
</div>
</div>
完成字符串连接。你在+ operator调用中也错过了一个美元符号:
attr
兼容性允许您也可以使用ES6 $('#' + $(this).attr("data-content")).addClass("hidden");
,将您的JS封装在template literals中:
${}