rmarkdown中的Javascript代码块不起作用

时间:2019-08-01 14:39:24

标签: html r-markdown

我正在尝试创建一个带有按钮的Rmarkdown文档以复制文本片段。我已经在在线HTML编辑器中独立测试了该代码,并且当我按下按钮时,文本已成功复制到剪贴板。然后,我尝试使用书本作者Yihui Xie(https://bookdown.org/yihui/rmarkdown/)推荐的代码块在Rmarkdown文档中使用它。将Rmarkdown文档编译为.html时,该按钮不起作用(RStudio用于编译)。

    ---
    author: "Nick Riches"
    output:
      html_document:
        number_sections: no
        toc: yes
        toc_float:
          collapsed: yes
      pdf_document:
        toc: yes
      word_document:
        toc: yes
    ---

    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = TRUE)
    ```

    ```{js, echo=FALSE}

    function myFunction() {
      var copyText = document.getElementById("myInput");
      copyText.select();
      document.execCommand("copy");
      alert("Copied the text: " + copyText.value);

    ```


    <p>Click on the button to copy the text from the text field. Try to paste the text (e.g. ctrl+v) afterwards in a different window, to see the effect.</p>

    <input type="text" value="Hello World" id="myInput">
    <button onclick="myFunction()">Copy text</button>

1 个答案:

答案 0 :(得分:0)

我在Romain Lesur的github上找到了一个名为klippy的软件包。这就是使用它的方式

```{r, echo=FALSE, message=FALSE}
library(devtools)
devtools::install_github("RLesur/klippy")
```


```{r klippy, echo=FALSE, include=TRUE}
klippy::klippy(lang = "markdown")
```

```{markdown}
Here insert text to be copied
```

位于https://rlesur.github.io/klippy/reference/klippy.html

的完整语法参考