我可以使用jquery字符串来定位id吗?

时间:2018-01-01 19:22:12

标签: javascript jquery string custom-data-attribute targeting

我目前正在尝试构建菜单,我希望根据我按下的按钮进行动态定位。

所以例如,我的jquery代码看起来像这样

resource :user_profile

但我想知道我是否可以写一些类似

的内容
jQuery(function($) {
  $("button").on("click", function() {
    $('.nav-content').find('> .nav-links').addClass("hidden");
    $('#students').removeClass("hidden");
  });
});

以下是JSFiddle的链接,可以查看代码的完整内容

3 个答案:

答案 0 :(得分:3)

正确的语法是

var currentId = $(this).attr('data-content');
$('#'+currentId).addClass("hidden");

答案 1 :(得分:0)

使用JS中的+ operator完成字符串连接。您在attr调用中错过了一个美元符号:

$('#' + $(this).attr("data-content")).addClass("hidden");

兼容性允许您也可以使用ES6 template literals,将您的JS封装在${}中:

$(`#${$(this).attr(data-content)}`).addClass("hidden");

答案 2 :(得分:0)

以下是jsfiddle中代码的更新版本及其解决方案:js代码注释中的说明。



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;
}

<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>
&#13;
&#13;
&#13;

相关问题