在网上搜索了很多次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;发布于 2011-12-29 06:04:00
实际上,您并没有将新链接添加到DOM树中,这就是它不会出现在HTML文档中的原因。当您需要在文档中已经存在的另一个IHTMLElement上调用insertAdjacentHTML()时,您是在新的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; 更新:使用IHTMLDocument2.execCommand()将所选文本更改为<a>标记
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; https://stackoverflow.com/questions/8661058
复制相似问题