[英]How would I use a data-attribute in HTML to fill a link and image source with a link from a database?
I have a database that has a table with a column called "link" that holds a link such as this " http://www.google.com ", and a column called "image" that holds this " http://www.placehold.it/500x500 ". 我有一个数据库,该数据库的表包含一个名为“ link”的列,其中包含一个链接,例如“ http://www.google.com ”,另一个名为“ image”的列中包含此“ http:// www .placehold.it / 500x500 ”。
I then have the following html: 然后,我有以下html:
<a href="" data-field="link">
<img src="" data-field="image">
</a>
I have a PHP backend that uses JSON and a JQuery plugin to retrieve and populate information but I don't know how to fill the href"" and src"" attributes specifically. 我有一个使用JSON的PHP后端和一个JQuery插件来检索和填充信息,但是我不知道如何具体填充href“”和src“”属性。
How can I do this with JQuery/JavaScript? 我该如何使用JQuery / JavaScript?
Is that the the thing you want? 那是你想要的东西吗?
$("a[data-field='link']").attr("href",yourValue);
$("img[data-field='image']").attr("src",yourAnotherValue);
Do you mean something like this http://jsfiddle.net/0jLad8hj/ 您的意思是这样的吗http://jsfiddle.net/0jLad8hj/
$(document).ready(function(){
$('a').attr('href', function(){
return $(this).data('field');
}).find('img').attr('src', function(){
return $(this).data('field');
});;
});
Use the .attr function from jQuery. 使用jQuery中的.attr函数。 The first value is the attribute to set and the second is the value.
第一个值是要设置的属性,第二个值是该值。 .data gets the data-attribute
.data获取数据属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.