我想在循环内使用 javascript/jquery 设置 div 的值/文本,但我不知道如何实现它。我需要帮助解决这个问题。
目标:
- 从数据库检索数据。
- 使用 javascript/jquery(在循环内)从数据库设置元素的值。
- 将值设置为链接
我有来自 links
表的 a_link
列,其中包含 ff。值:
- www.google.com
- https://www.google.com
- www.stackoverflow.com
这是我的代码:
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$thelink = $rowlink['a_link'];
?>
<div class = "row">
<span id = "linkhere"></span>
</div>
<script>
var link = "<?php echo $thelink; ?>";
$("#linkhere").html(urlify(link));
function urlify(text) {
var urlRegex = /(((https?:\/\/)|(www\.))[^\s]+)/g;
//var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url,b,c) {
var url2 = (c == 'www.') ? 'http://' +url : url;
// return '<span style = "color:blue;text-decoration:underline">' + url + '</span>';
return '<a href="' +url2+ '" target="_blank">' + url + '</a>';
})
}
</script>
<?php
}
?>
任何帮助将不胜感激。谢谢。
最佳答案
@aimme is technically not wrong about using a different database library. Please read "Why shouldn't I use mysql_* functions in PHP?" for reasons why not to use mysql_ and for some neat alternatives, some tutorials, and some good reads. (yes, all in the same page! just scroll down)
我认为您正在尝试:
- 显示
<div>
类“行”的- 带有
<a>
里面的标签使用“links”表的“a_link”列作为 href 和标签。- 标签的 href 必须始终具有方案 (http://)。
- 带有
只有 PHP 和 HTML
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$regexMatches = array();
// removed (what seemed to be) needless groups in regex
$urlFound = preg_match("@((https?:\/\/|www\.)[^\s]+)@",$theLink,$regexMatches);
if($urlFound === 1) {
// only add http:// if http:// was not detected
$href = ($regexMatches[2] === "www." ? "http://" : "") . $theLink;
?>
<div class="row">
<a href="<?php echo $href; ?>" target="_blank"><?php echo $theLink; ?></a>
</div>
<?php }
}
?>
如果 a_link 不包含“http://”或“www”,则此代码不会回显一行。在里面。因此 google.com 将不会显示。
值得注意的是,正如所写,正则表达式适用于“url”,例如“applewww.google.com”。不知道这是否重要。在正则表达式的开头添加“^”可能会解决问题(例如: preg_match("@^((https?:\/\/|www\.)[^\s]+)@",$theLink,$regexMatches);
)
(更好|不同)的解决方案可以使用parse_url($url)
<?php
$querylink = "SELECT * from links";
$resultlink = mysql_query($querylink);
while ($rowlink = mysql_fetch_array($resultlink))
{
$theLink= $rowlink['a_link'];
$href = (parse_url($theLink,PHP_URL_SCHEME) === NULL ? "http://" : "") . $theLink;
?>
<div class="row">
<a href="<?php echo $href; ?>" target="_blank"><?php echo $theLink; ?></a>
</div>
<?php
}
?>
但是,使用 parse_url() 意味着将显示任何旧字符串(而第一个解决方案不会显示任何没有 http://或 www 的链接。)但是因为您从名为 ' 的表中提取数据,链接' 可以安全地假设所有内容都是有效路径。
关于javascript - 使用 javascript/jquery 设置 div 的值/文本 - 在 php 循环内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32545840/