css / html基于数据属性的自定义href

时间:2017-09-05 20:48:52

标签: javascript html css css3

是否可以根据data-schemaid="my-id-name"

等数据属性创建自定义href

我见过的所有例子都使用了id。

例如:https://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_scrollspy&stacked=h

我的html是动态生成的,没有类或ID,但看起来像这样:

<div data-schemaid="my-id-name"></div>

我尝试使用与示例相同的逻辑,但这不起作用。

2 个答案:

答案 0 :(得分:1)

是的,您可以根据任何其他元素的任何方面设置元素的任何方面。你需要选择一个应该发生的时间点(页面加载,点击另一个元素等)。

这是一个示例,用于设置<a>元素,href元素与页面加载时data-schemaid的{​​{1}}属性值相匹配,并附加该元素div元素放入文档中(顺便说一句,您确实知道您显示的a的值本身并不是有效的网址,需要调整为有效导航to,对吗?如果你只想点击div导航(滚动)到<a>,你只需要预先添加&#34;#&#34;到它,如下所示。):

&#13;
&#13;
<div>
&#13;
// Set up an event handler for when the document is parsed and ready to be interacted with:
window.addEventListener("DOMContentLoaded", function(){
   // Scan the document for the dynamically generated div that has a `data-schemaid` attribute
   var theDiv = document.querySelector("div[data-schemaid]");
   
   var newA = document.createElement("a");      // Create a new <a> element
   newA.href = "#" + theDiv.dataset.schemaid;         // Set the href to the div's attribute value
   newA.textContent = "Click Me";               // Give the new <a> some text to click on
   document.body.appendChild(newA);             // Append the new <a> to the end of the body
});
&#13;
&#13;
&#13;

或者,如果文档中已存在<div data-schemaid="my-id-name"> </div>元素(并且不需要追加),那么解决方案会更简单:

&#13;
&#13;
<a>
&#13;
// Set up an event handler for when the document is parsed and ready to be interacted with:
window.addEventListener("DOMContentLoaded", function(){
   // Scan the document for the dynamically generated div that has a `data-schemaid` attribute
   var theDiv = document.querySelector("div[data-schemaid]");
   
   var speicalA = document.getElementById("specialA");   // Get a reference to the <a> element
   speicalA.href = "#" + theDiv.dataset.schemaid;         // Set the href to the div's attribute value

});
&#13;
&#13;
&#13;

答案 1 :(得分:1)

如果我正确地假设您需要一个href="my-id-name"的锚标记带您到属性为data-schemaid="my-id-name"的元素,那么只需要找到该元素并调用{{3 }} 在上面。如果想要为滚动设置动画,请参阅此scrollIntoView(true)

//use getAttribute("href") instead of this.href as 
//this.href will get a url based on the actual href attribute
var schemaid = this.getAttribute("href");

//use css attribute selector to find the target element
var target = document.querySelector(`[data-schemaid="${schemaid}"]`);
if(target){
  target.scrollIntoView(true);
}

演示

document.querySelector('#anchor').addEventListener("click",function(event){
   event.preventDefault();
   var schemaid = this.getAttribute("href");
   var target = document.querySelector(`[data-schemaid="${schemaid}"]`);
   if(target){
     target.scrollIntoView(true);
   }
});
.spacer {
  height:1440px;
}
<a id="anchor" href="my-schemaid">Click me</a>
<div class="spacer"></div>
<div data-schemaid="my-schemaid">The target div</div>
<div class="spacer"></div>