首页 > 解决方案 > Why is JQuery not affecting tables in RMarkdown?

问题描述

I'm trying to use JQuery on HTML tables in RMarkdown. Specifically, I'm trying add row classes to certain rows of a DT::datatable using JQuery.

I've tested the jQuery code in jsFiddle and that works fine. I've also tested basic jQuery code (changing colour of headers) in RMarkdown. This also works. I've not managed to get jQuery relating to tables working on DT::datatable in RMarkdown.

The code below is from an .Rmd file.

# Test
{js jQuery codechunk}
// Test that jQuery works in Rmd
$('.h1').css('color', 'red')

// Updating classes does not work
$("tr:contains('Mazda')").addClass('Mazda');

// Colour styling also does not work
$("tr:contains('Mazda')").css("color", "red")
{r R codechunk}
library(DT)
  DT::datatable(mtcars)

I expect that when I inspect the table, the rows with "Mazda" will be coloured red and the will have the class "Mazda".

I just see the plain DataTable, and the row classes are the standard ones.

标签: jqueryrdatatabledatatablesr-markdown

解决方案


我懂了!请参阅文档的第 2.9 节“callback论据”。

我进行了以下更改,您的代码就像一个魅力。

  • 将您想做的所有事情都包装在一个函数中。
  • callback从 的参数调用该函数DT::datatable()
  • (我也进行了更改.h1h1使示例的这一部分工作。)

顺便说一句,漂亮的包裹。感谢您向我介绍它!

---
title: "It works!"
author: "trianglegirl"
date: "May 20, 2019"
output: html_document
---

```{js jQuery-codechunk}
const trianglegirl_function = function() {

  // Test that jQuery works in Rmd
  $('h1').css('color', 'red');

  // Updating classes does not work
  $("tr:contains('Mazda')").addClass('Mazda');

  // Colour styling also does not work
  $("tr:contains('Mazda')").css("color", "red");
};
```

```{r R-codechunk}
library(DT)
DT::datatable(mtcars, callback = JS('trianglegirl_function();'))
```

推荐阅读