在网上搜索了很多createElement和insertAdjacentHTML后,我想出了这段代码。执行代码时,链接不会插入HTML。该链接是本地文件的链接。我做错了什么?
var
HTMLDocument2Ifc: IHTMLDocument2;
iLinkString: string;
iTopicString: string;
iLink: IHTMLElement;
begin
FormInsertLink := TFormInsertLink.Create( Self );
try
if FormInsertLink.ShowModal = mrOk then
begin
// <A HREF="file://..\html\author.htm">Author</A>
HTMLDocument2Ifc := TopicWebBrowser1.Document as IHTMLDocument2;
iLinkString := FormInsertLink.EditLink1.Text; // file://..\html\author.htm
iTopicString := FormInsertLink.EditTopic1.Text; // Author
iLink := HTMLDocument2Ifc.createElement('a');
iLink.InnerText := iLinkString;
iLink.insertAdjacentHTML('afterEnd', '<A HREF="' + iLinkString + '">' + iTopicString + '</A>');
end;
finally
FormInsertLink.Free;
end;
答案 0 :(得分:8)
您实际上并未将新链接添加到DOM树,这就是它不会出现在HTML文档中的原因。当您需要在文档中已存在的另一个insertAdjacentHTML()
上调用IHTMLElement
时,您在新IHTMLElement
上调用var
iDoc: IHTMLDocument2;
iElement: IHTMLElement;
begin
FormInsertLink := TFormInsertLink.Create( Self );
try
if FormInsertLink.ShowModal = mrOk then
begin
iDoc := TopicWebBrowser1.Document as IHTMLDocument2;
iElement := iDoc.all('some existing element');
iElement.insertAdjacentHTML('afterEnd', '<A HREF="' + FormInsertLink.EditLink1.Text + '">' + FormInsertLink.EditTopic1.Text + '</A>');
end;
finally
FormInsertLink.Free;
end;
,例如:
appendChild()
或者,改为使用var
iDoc: IHTMLDocument2;
iLink: IHTMLAnchorElement;
begin
FormInsertLink := TFormInsertLink.Create( Self );
try
if FormInsertLink.ShowModal = mrOk then
begin
iDoc := TopicWebBrowser1.Document as IHTMLDocument2;
iLink := iDoc.createElement('A') as IHTMLAnchorElement;
iLink.href := FormInsertLink.EditLink1.Text;
(iLink as IHTMLElement).innerText := FormInsertLink.EditTopic1.Text;
(iDoc.body as IHTMLDOMNode).appendChild(iLink as IHTMLDOMNode);
end;
finally
FormInsertLink.Free;
end;
方法:
<a>
更新:使用var
iDoc: IHTMLDocument2;
iSelection: IHTMLSelectionObject;
iRange: IHTMLTxtRange;
begin
FormInsertLink := TFormInsertLink.Create( Self );
try
if FormInsertLink.ShowModal = mrOk then
begin
iDoc := TopicWebBrowser1.Document as IHTMLDocument2;
iSelection := iDoc.selection as IHTMLSelectionObject;
iRange := iSelection.createRange() as IHTMLTxtRange;
iRange.pasteHTML('<a href="' + FormInsertLink.EditLink1.Text + '">' + FormInsertLink.EditTopic1.Text + '</a>');
// or:
// iRange.pasteHTML('<a href="' + FormInsertLink.EditLink1.Text + '">' + iRange.text + '</a>');
end;
finally
FormInsertLink.Free;
end;
标记包装所选文字:
<a>
更新:使用IHTMLDocument2.execCommand()
将所选文字更改为FormInsertLink := TFormInsertLink.Create( Self );
try
if FormInsertLink.ShowModal = mrOk then
begin
(TopicWebBrowser1.Document as IHTMLDocument2).execCommand('CreateLink', False, FormInsertLink.EditLink1.Text);
end;
finally
FormInsertLink.Free;
end;
代码:
{{1}}