我正在尝试这样做,所以我可以编辑一个有字符串的div。如果字符串包含链接,那么页面将在锚标记内加载该链接并允许其被点击。
下面是从数据库中获取帖子的代码,检查是否有链接并显示链接(编辑:我决定将php更改为javascript,但现在它没有不更新数据库):
<div id="reply<?php echo $rows['a_id']; ?>">
<script>
var text = "<?php echo $rows['a_answer']; ?>";
text = text.replace(/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g,
'<a href="$1" rel="nonfollow" target="_blank">$1</a>'
);
document.write(text);
</script>
</div>
<?php
if($editPost == true) {
?>
<div id="postId"><?php echo $rows['id'];?></div>
<button id="editPost">Edit</button>
<button id="savePost">Save</button>
<button id="cancelPost">Cancel</button>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#savePost').hide();
$('#cancelPost').hide();
});
</script>
<?php
}
?>
</div>
<script type="text/javascript">
$(document).ready(function(argument) {
$('#editPost').click(function() {
$('#post').attr('contenteditable','true');
$('#post').css('background','white');
$('#post').css('border','solid 1px');
$('#savePost').show();
$('#cancelPost').show();
$('#editPost').hide();
});
$('#savePost').click(function() {
// Get edit field value
$detail = $('#post').html();
$id = $('#postId').html();
$.ajax({
url: 'editPost.php',
type: 'post',
data: {detail: $detail, id: $id},
datatype: 'html',
});
$('#editPost').show();
$('#savePost').hide();
$('#cancelPost').hide();
$('#post').attr('contenteditable','false');
$('#post').css('background','#D8D8D8');
$('#post').css('border','none');
});
$('#cancelPost').click(function() {
$('#editPost').show();
$('#savePost').hide();
$('#cancelPost').hide();
$('#post').attr('contenteditable','false');
$('#post').css('background','#D8D8D8');
$('#post').css('border','none');
});
});
</script>
?>
editpost.php:
<?php
$host = "host"; // Host name
$user = "username"; // Mysql username
$password = "password"; // Mysql password
$db_name = "database"; // Database name
$tbl_name = "fquestions"; // Table name
// Connect to server and select databse.
$conn = mysqli_connect($host, $user, $password)or die("cannot connect");
mysqli_select_db($conn, $db_name)or die("cannot select DB");
$detail = $_POST['detail'];
$id = $_POST['id'];
// Add your validation and save data to database
echo $detail;
echo $id;
$datetime = date("d/m/y H:i:s"); // create date and time
$sql = "UPDATE $tbl_name SET detail = '$detail', datetime = 'Edited: $datetime' WHERE id= '$id'";
$result = mysqli_query($conn, $sql);
?>
我可以编辑没有链接的文本就好了,但是里面有锚点的文本会导致问题。我甚至不得不使用<p>
代替<div>
,或者甚至在编辑之前它也无法显示。