[英]How to read data between two html tags as text
I am working on a project which needs to extract text form a predefined div
tag. 我正在开发一个项目,需要从预定义的
div
标签中提取文本。
My requirement is to send the content in the target div
in a email body. 我的要求是在电子邮件正文中发送目标
div
中的内容。 I have to use javascript
or php
for this task. 我必须使用
javascript
或php
来完成这项任务。
The Process : When a given link will be clicked; 过程:点击给定链接时; a
javascript
function will trigger and read that target div
. 一个
javascript
函数将触发并读取该目标div
。 The content of the div
will be then submitted to server in dynamic form. 然后
div
的内容将以动态形式提交给服务器。
What options I have to get this task done? 我有什么选择来完成这项任务?
Thanks. 谢谢。
I would get the innerHTML
of the div. 我会得到div的
innerHTML
。 So if your div is div_obj: 所以如果你的div是div_obj:
var div_obj = document.getElementById("...");
alert(div_obj.innerHTML);
So assuming that you have something that looks like 所以假设你有一些看起来像的东西
<a href="#" onClick="someClickHandler(); return false;">Click Here</a>
<div id="foo">Hello World!</div>
I recommend using jQuery : 我建议使用jQuery :
<script type="text/javascript">
function someClickHandler() {
var text = $("#foo").text();
$.get("url_on_the_server", {some_query_parameter_name: text}, function(response){
// do something with the response you get back from the server
});
}
</script>
Here's what this is doing: 这是这样做的:
The onClick
attribute causes the someClickHandler
function to be called when the link is clicked. onClick
属性会在单击链接时调用someClickHandler
函数。 Because we put return false
in that attribute, the browser will not try to follow the link; 因为我们在该属性中放置
return false
,所以浏览器不会尝试关注该链接; instead when clicked it will just execute the click handler and stop. 相反,当点击它时,它将只执行点击处理程序并停止。
Saying $("#foo")
finds the element on the page with an id
of "foo", as documented here . 说
$("#foo")
发现页面上的元素与id
的“富”,作为记录在这里 。 Saying $("#foo").text()
returns everything inside that div as text, as documented here . 说
$("#foo").text()
将div中的所有内容作为文本返回,如此处所述 。
The $.get
call is explained at depth in the jQuery documentation here . 这里的jQuery文档深入解释了
$.get
调用。 Basically you're making an AJAX request to the server and passing the text from the div as a query parameter. 基本上,您正在向服务器发出AJAX请求,并将div中的文本作为查询参数传递。 The function you pass to
$.get
defines what you do with the response you get back from the server. 传递给
$.get
的函数定义了从服务器返回的响应。
Of course, you could also use the jQuery click method instead of manually setting the onClick
attribute yourself, but I figured that this way would be somewhat more intuitive for a beginner. 当然,您也可以使用jQuery click方法而不是自己手动设置
onClick
属性,但我认为这种方式对于初学者来说会更直观一些。
Indeed, I'd give the div an id and then use the innerHTML method to get its contents. 实际上,我给div一个id然后使用innerHTML方法来获取它的内容。
After that, you could use XMLHttpRequest to submit the contents to the server. 之后,您可以使用XMLHttpRequest将内容提交到服务器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.