[removed] get

前端 未结 6 986
名媛妹妹
名媛妹妹 2020-11-30 06:18

If the img below is present


and the script is



        
相关标签:
6条回答
  • 2020-11-30 06:51

    in this situation, you would grab the element by its id using getElementById and then just use .src

    var youtubeimgsrc = document.getElementById("youtubeimg").src;
    
    0 讨论(0)
  • 2020-11-30 06:56
    var youtubeimgsrc = document.getElementById('youtubeimg').src;
    document.write(youtubeimgsrc);
    

    Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/

    0 讨论(0)
  • 2020-11-30 06:56

    Use JQuery, its easy.

    Include the JQuery library into your html file in the head as such:

    <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    </head>
    

    (Make sure that this script tag goes before your other script tags in your html file)

    Target your id in your JavaScript file as such:

    <script>
    var youtubeimcsrc = $('#youtubeimg').attr('src');
    
    //your var will be the src string that you're looking for
    
    </script>
    
    0 讨论(0)
  • 2020-11-30 07:09

    How about this for instance :

    var youtubeimgsrc = document.getElementById("youtubeimg").getAttribute('src');
    
    0 讨论(0)
  • 2020-11-30 07:16

    If you don't have an id on the image but have a parent div this is also a technique you can use.

    <div id="myDiv"><img src="http://www.example.com/image.png"></div>
    
    var myVar = document.querySelectorAll('#myDiv img')[0].src
    
    0 讨论(0)
  • 2020-11-30 07:17

    As long as the script is after the img, then:

    var youtubeimgsrc = document.getElementById("youtubeimg").src;
    

    See getElementById in the DOM specification.

    If the script is before the img, then of course the img doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body element.


    Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:

    <img id="foo" src="/images/example.png">
    

    ...the src reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com, document.getElementById("foo").src would give you "http://www.example.com/images/example.png".

    If you wanted the src attribute's content as is, without being resolved, you'd use getAttribute instead: document.getElementById("foo").getAttribute("src"). That would give you "/images/example.png" with my example above.

    If you have an absolute URL, like the one in your question, it doesn't matter.

    0 讨论(0)
提交回复
热议问题