开发者

Databinding Rails 3 with jQuery

I am working on a project to learn both Ruby on Rails and JQuery/Javascript.

For sake of an example let's say I have the basic Rails tutorial of a post with a title and some content.

If I am looking at the "Show" view for a single post how would I access the title for use in Jquery functions?

For example if I wanted to display an alert that said "This post is tit开发者_运维技巧led 'X'" when the page loads how would I structure the alert("This post is titled" + "..."); for the "..." to be replaced with the post.title value from the record?


This really doesn't have anything to do with rails, but rather just the html and css of the view generated by the show action. We need to see the html from that view to say for sure.

Jquery works with css selectors, so if you title is in an <h1> element, you might use:

alert($('h1').html);


jQuery will work on the HTML page once rendered; mark the HTML entity containing the title with an id and access its content with the standard .text().

In example in show.html.erb:

<h1 id="post_title"><%= @post.title %></h1>
...
<script>
  var str = $("h1#post_title").text();
  alert(str);
</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜