简体   繁体   中英

Rendering a partial view. Javascript files dont apply to that rendered view?

I am using nodejs. And calling something like the following from a javascript file:

$("#right").append(resp);

I then initialize it as a datatable but all the functions (like doubleclick) defined on datatables don;t work. If I copy the code for the doubleclick into the console it works.

What am I doing wrong?

Edit: more info. So what I have now is when a user logs in it displays their playlists in a sidebar using ajax. When the playlist is clicked it loads that playlists. However, the code in application.js(loaded initially) does not apply to the playlists unless the page is fully reloaded.

Here is some code I have:

    $.ajax({
  type: "POST",
  url: '/login',
  data: {  email: email, password: pass },
  success: function(result) {
    $.get('/toop', function(data) {
    console.log(data);
    if (data == "fail") {
      alert("error");
    } else {
    $("#header").html(data);
    $(document).trigger('close.facebox');
    $.get('/getPlaylists' , function(playlists) {
    $("#left").html(playlists);
    });

This just gets the playlists for the users and puts them on the sidebar. Now in the application.js file I have:

    $(".user-playlist").click(function(e) {
    var playlist = e.target;
    var id = $(playlist).attr('data-playlist');

. . . .

But it only detects a click of the playlist if I do a full refresh of the page. Just rendering it using ajax doesnt. I am doing {layout: false} when getting the new view. Do I have to reload application.js? I am new to node (and web dev). Thanks

The click event handler will only be applied to the set of elements which match .user-playlist when $(".user-playlist") is called. To see which elements those are, open the web inspector (or Firebug) and add this line just before the JavaScript snippet you included in your post:

console.log($(".user-playlist"))

You should see an empty array on the page where the playlist is loaded from Ajax, and at least one item on the page after a full refresh.

To attach the event handler even for elements which are not on the page yet, read the documentation for the on method (specifically, the functionality that used to belong to the live method).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM