如何将 URL 从图像的 src 属性复制到 jQuery 中的 href 属性? [英] How can I copy a URL from an image's src attribute to an href attribute in jQuery?

查看:25
本文介绍了如何将 URL 从图像的 src 属性复制到 jQuery 中的 href 属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 HTML 代码

<ul class="anythingSlider"><li class="面板活动页面"><div class="content clearfix" style="width: 100%; height: 100%;"><a href="http://www.example.com/a.jpg" class="focusedLink"><img src="http://www.example.com/a.jpg"/></a><div class="slider-text">Lorem ipsum dolor sat amet, consectetur adipisicing elit<a title="" href="#">阅读更多</a>

<li class="面板活动页面"><div class="content clearfix" style="width: 100%; height: 100%;"><a href="http://www.example.com/a.jpg" class="focusedLink"><img src="http://www.example.com/a.jpg"/></a><div class="slider-text">Lorem ipsum dolor sat amet, consectetur adipisicing elit<a title="" href="#">阅读更多</a>

正如您在 div.content > 中看到的那样>img 有特定位置的图像.如何将 URL 从此图像复制到 div.slider-text > 的 href 属性一个?

我尝试了 jQuery 的 each() 方法,但无法让它工作.

解决方案

试试这个;

$(document).ready(function() {$('.anythingSlider .panel').each(function() {var $this = $(this);//从 img 中获取 src 属性var url = $this.find('.content a img').first().attr('src');//在 a 上设置 href 属性$this.find('.content .slider-text a').first().attr('href', url);});});

This is my HTML code

<div class="anythingWindow">
    <ul class="anythingSlider">
      <li class="panel activePage">
        <div class="content clearfix" style="width: 100%; height: 100%;">
          <a href="http://www.example.com/a.jpg" class="focusedLink">
            <img src= "http://www.example.com/a.jpg"/>
          </a>
          <div class="slider-text">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit
            <a title="" href="#">Read More</a>
          </div>
        </div>
      </li>

      <li class="panel activePage">
        <div class="content clearfix" style="width: 100%; height: 100%;">
          <a href="http://www.example.com/a.jpg" class="focusedLink">
            <img src= "http://www.example.com/a.jpg"/>
          </a>
          <div class="slider-text">
            Lorem ipsum dolor sit amet, consectetur adipisicing elit
            <a title="" href="#">Read More</a>
          </div>
        </div>
      </li>
    </ul>
 </div>

As you can see in div.content > a > img there is image with specific location. How can I copy the URL from this image to the href attribute of div.slider-text > a?

I tried jQuery's each() method, but couldn't get it to work.

解决方案

Try something like this;

$(document).ready(function() {

  $('.anythingSlider .panel').each(function() {
     var $this = $(this);

     // Get src attribute from img
     var url = $this.find('.content a img').first().attr('src');

     // Set href attribute on a
     $this.find('.content .slider-text a').first().attr('href', url);

  });

});

这篇关于如何将 URL 从图像的 src 属性复制到 jQuery 中的 href 属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆