javascript - 使用 href 代替输入

标签 javascript php jquery html

我有AJAX功能,但我不擅长AJAX。我想将一个值从 PHP 传递到 AJAX。我设法通过使用来做到这一点:

<input type="text" id="price" onclick='ajaxFunction()' value="<?php echo $id; ?>" />

然后在我的 AJAX 中:

document.getElementById('price').value;

但我想通过使用 HTML a href 来使其工作。

任何人都可以帮助我找到可能的方法吗?

提前致谢!

最佳答案

anchor<a>标签没有 value ,而是 innerHTML 。使用这种方式:

<a id="price" href="#something">50.00</a>
document.getElementById('price').innerHTML; // 50.00
document.getElementById('price').getAttribute("href"); // #something

要设置这些值,您可以使用相同的东西:

document.getElementById('price').innerHTML = responseText;
document.getElementById('price').setAttribute("href", responseText);

和往常一样,最好以 JSON 形式响应以获得好的东西:

responseText = {
    "price": 50.00,
    "link":  '#something'
};

上面的 PHP 输出时,会是:

<?php header ("Content-type: application/json"); ?>
{
    "price": 50.00,
    "link":  '#something'
}

您可以将其用作:

document.getElementById('price').innerHTML = responseText.price;
document.getElementById('price').setAttribute("href", responseText.link);

既然您添加了 ,我想添加此信息将使此答案变得有值(value)。我不确定你是如何调用 AJAX 函数的,但是这种调用方式非常棒。 jQuery 有一个内置的 AJAX 函数,您可以使用它:

$.post("path/to/php", {data: to_be_sent}, function (responseText) {
    responseText = JSON.parse(responseText);
    $("#price").attr("href", responseText.link).html(responseText.price);
});

在这种情况下阅读要容易得多:

$("#price").attr("href", responseText.link); // Gives you the #something
$("#price").html(responseText.price);        // Gives you the 50.00

关于javascript - 使用 href 代替输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31383155/

相关文章:

javascript - 从 JSON 数组获取列表结果

javascript - 如何将 cookie 从 javascript 更改为 angularjs

php - 前 x 行的字段总和,每个后续行的偏移量 +1

PHP filter_input : how to return NULL when it is empty from the input

Javascript 函数无法返回元素

javascript - 偏移量不能将 div 返回到 0,0?

javascript - 在 JavaScript 中使用 "defineProperty"后重置对象属性 getter/setter

javascript - 工具提示(标题 ="...")不会在 Firefox 中显示

javascript - 水平 HTML5 mediaelementjs 音量 slider

php - 在循环中插入 sql 查询是好事还是坏事?