简体   繁体   English

如何使用HTML中的数据属性用数据库中的链接填充链接和图像源?

[英]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.

相关问题 如何使用数据属性将值从数据库传递到 jquery - How to use data-attribute to pass values from database to jquery 如何保存单击的链接的数据属性以与JavaScript中的其他函数一起使用 - How to save a clicked link's data-attribute for use with other functions in JavaScript 使用HTML中的数据属性代替图片进行javascript编辑 - Use data-attribute in HTML for image instead of javascript editing 如何从 php 变量中获取 html 数据属性字符串 - How to get html data-attribute string from a php variable 如何正确访问HTML元素的数据属性? - How do I properly access the data-attribute of an HTML element? 添加数据属性及其值以与纯JavaScript链接 - Add data-attribute and its value to link with pure javascript 使用数据属性中的值选中链接点击复选框(是否可能发生更改冲突?) - Check a checkbox on link click using value from data-attribute (possible on change clash?) 单击骨干路由器中的链接时如何传递事件(访问数据属性) - how to pass the event (to access data-attribute) when clicking link in Backbone router 如何使用数据属性而不是它们的值链接两个下拉列表? - How to link two dropdown lists using data-attribute instead of their values? 我什么时候应该使用“隐藏文本框”,什么时候应该使用(html 5)“数据属性”? - When should I use a “Hidden TextBox” and when should a use a (html 5) “data-attribute”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM