如何在Dart中创建HTML链接?

问题描述:

我想要与Dart建立一个HTML连结。

I would like to create an HTML link with Dart.

在HTML中我会写:

You can click <a href="url_1">here</a> and <a href="url_2">there</a>.

我不知道如何在Dart中做。我试过像:

I do not know how to do it in Dart. I tried something like:

LinkElement link1;
link1.href = "url1";

我不知道如何插入 link1

有很多方法可以做到这一点。这里有两个:

There are many ways to do it; here are two:

import 'dart:html';

void main() {
  // Method one: build everything from scratch
  var p = new ParagraphElement();
  var link1 = new AnchorElement()
    ..href = 'url_1'
    ..text = 'here';
  var link2 = new AnchorElement()
    ..href = 'url_2'
    ..text = 'there';

  p ..appendText('You can click ')
    ..append(link1)
    ..appendText(' and ')
    ..append(link2)
    ..appendText('.');

  document.body.children.add(p);

  // Method two: just set `innerHtml` with an HTML fragment
  var p2 = new ParagraphElement()
    ..innerHtml = 'You can click <a href="url_1">here</a> '
                  'and <a href="url_2">there</a>.';

  document.body.children.add(p2);
}

你可以在这两个极端之间做一些事情,一个HTML文件,你需要适当的 id s或 class es,访问他们从Dart。从你的问题很难知道你的需求是什么,但这些选项应该包括你认为适合你的情况。

You can do something in between those two extremes, or you could write it in an HTML file as you're used to, giving the pieces you need appropriate ids or classes so you can access them from Dart. It's hard to know from your question exactly what your needs are, but these options should cover whatever you find appropriate for your case.