开发者

Why can't I get my jQuery code to correctly structure my HTML?

开发者 https://www.devze.com 2023-02-17 00:02 出处:网络
I\'m writing an app with Ruby on Rails, jQuery and the Embedly API. I write a video partial like so: <%= div_for video do %>

I'm writing an app with Ruby on Rails, jQuery and the Embedly API. I write a video partial like so:

<%= div_for video do %>

<%= link_to 'video', video.video_开发者_C百科url, :class => 'oembed' %>

<% end %>

And render that partial in the index view:

<div id ='video_div'>
  <%= render @videos %>
</div>

Then my application.js file takes the link and uses the Embedly API to embed the video and display the thumbnail. I initially hide the video with CSS, and I want the each video with its respective thumbnail to be in its own div. This means that I want every video/thumbnail pair to be in its own div, so that I can position the thumbnail directly on top of the video. I tried doing this:

$('a.oembed').embedly({maxWidth:300,'method':'replace'}).bind('embedly-oembed', function(e, oembed){ 
    var id = $(this).parent().attr('id');
    $(id).append($("<img>", { src: oembed.thumbnail_url, width:200 }));
});

My thinking is that since the div_for embedded ruby creates a div with a unique id surrounding each video that was originally a link, I would go to the parent of the link (the div with the unique id), and get the unique id attribute, and then append the thumbnail to that div. However, after checking my HTML code in the browser, the thumbnail is not getting appended. What am I doing wrong, and how can I get what I want?


It looks like the problem is this line:

 $(id).append($("<img>", { src: oembed.thumbnail_url, width:200 }));

It should be:

$('#' + id).append($("<img>", { src: oembed.thumbnail_url, width:200 }));

However, $(this).parent() is already returning the element you are after, so all the work you are doing with its id is not needed:

$(this).parent().append("<img>" ...);


My suspicion would be that either this isn't what you think it is as embedly is creating more html, so where you are trying to navigate to the id it might not be getting to what you think should be there.

If you have a few elements on the page I'd put an alert around the id to check its value.

You can also call parent() with an explict selector of what to find, so if embedly doesn't generate any div's you could add parent('div').

You also don't need to look up the id to append, you can do it directly from parent() i.e. parent().append(). You save yourself a selector call that way.

0

精彩评论

暂无评论...
验证码 换一张
取 消