2

I would like to create an HTML link with Dart.

Where in HTML I would write:

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

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

LinkElement link1;
link1.href = "url1";

I do not know how to insert the link1 object within a static sentence like the HTML example above.

4

1 回答 1

2

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);
}

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.

于 2013-05-15T21:44:18.350 回答