简体   繁体   English

使用jQuery从另一个文件中的元素获取数据值

[英]Get data-value from element in another file with jQuery

So basically I have some elements with some data-values in a file . 所以基本上我在文件中有一些具有某些数据值的元素。 I want to dynamically create links to them using those data-values to type the text , href etc. 我想使用这些数据值键入文本href等动态创建指向它们的链接。

For example, I have two divs, id'ed first and second . 例如,我有两个div,分别是firstsecond They have importance values, respectively "most important" and "least important". 它们具有importance值,分别为“最重要”和“最不重要”。

I want to create two links to them, with the phrase "This is a link to the most/least important div" using JavaScript/jQuery. 我想使用JavaScript / jQuery创建两个链接,用短语“这是到最/最重要的div的链接”。 Below is a non-working example. 以下是无效示例。

File a.html (ommiting headings and such, ofc): 归档a.html (省略标题等):

<div id='first' data-importance='most important'>This is the first div.</div>

<div id='second' data-importance='least important'>This is the second div.</div>

File b.html : 文件b.html

<p><a class='makelink' data-linkto='first'></a></p>

<p><a class='makelink' data-linkto='second'></a></p>

$(`.makelink`).each( function(){
  var target = $(this).data('linkto');
  $(this).attr('href','b.html#' + target);
  var imp = $('b.html #' + target).data('importance'); 
  $(this).html('Link to the ' + imp + ' div');
});

However nothing happens. 但是什么也没发生。 Any help is appreciated. 任何帮助表示赞赏。

Your code seems correct except the selector should be inside quote and the string generated in the html() is not properly formatted: 您的代码似乎正确,除了选择器应放在引号内并且html()生成的字符串格式不正确:

 $('.makelink').each( function(){ // Enclosed the selector with single/double qoute var target = $(this).data('linkto'); $(this).attr('href','#' + target); var imp = $('#' + target).data('importance'); $(this).html('Link to the '+ imp + ' div'); // concatenate the string with the variable using + }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id='first' data-importance='most important'>This is the first div.</div> <div id='second' data-importance='least important'>This is the second div.</div> <p><a class='makelink' data-linkto='first'></a></p> <p><a class='makelink' data-linkto='second'></a></p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM