markdown-it中a链接添加target属性
时间: 2024-10-19 20:13:36 浏览: 64
Markdown-it是一个轻量级的JavaScript Markdown解析器,它允许你在Markdown文本中插入超链接。如果你想要在生成的HTML中为链接添加`target`属性,通常是在创建自定义渲染规则的时候。`target`属性用于指定链接在新窗口(`_blank`)、当前窗口(`_self`)或其他选项中打开。
在Markdown-it插件中,你可以通过注册一个处理器(processor)来实现这个功能。这里有一个简单的例子:
```javascript
const md = require('markdown-it')();
const linkRenderer = md.renderer.rules.link_open || function(tokens, idx, options) {
let attr = tokens[idx].attrJoin('=');
// 添加 target 属性
if (options.target === '_blank') {
attr += ' target="_blank"';
}
return `<a ${attr}>`;
};
md.use(function(state) {
state.renderer.rules.link_open = linkRenderer;
});
let input = '[My Link](https://example.com "Optional Title")';
let output = md.render(input);
console.log(output); // 输出:<a href="https://example.com" target="_blank">My Link</a>
```
在这个例子中,我们修改了`link_open`渲染规则,在原有的基础上增加了`target="_blank"`属性。你可以根据需要调整`options.target`。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)