如何将JavaScript / JQuery变量传递给

时间:2018-09-04 12:55:17

标签: javascript jquery html variables

我正在尝试获取JavaScript / JQuery变量的值并将其存储在表TD值中,但没有成功...

到目前为止已经尝试过...

$("#someID").text(varNAME) / html(varNAME);

document.getElementById("someID").innerHTML = varNAME; 

document.querySelector("#someID").onclick=function() {
    document.querySelector('#someOtherID').textContent = document.getElementById('some_other_ID').value;
}

我的代码---

<td id="userName"></td>

JS变量-

var assign_user123 = MyApp.optionvalue123;
    alert(assign_user123);  /*i get value in alert box*/ 

MyApp是全局函数,而optionvalue123来自其他函数

编辑----

从这里,我正在获取用户名

<select title="" class="form-control" name="user" id="user" onchange="getValue(this)">
    <option value="">Select User to Assign</option>
    <?php foreach ($user as $row): ?>
        <option value="<?php echo $row->id; ?>"><?php echo $row->first_name . ' ' . $row->last_name; ?></option>
    <?php endforeach; ?>
</select>

JavaScript函数---

 var MyApp = {};

function getValue(sel) {
    MyApp.optionvalue2 = sel.value;

    var optionvalue = sel.value;
    alert(optionvalue);

    MyApp.optionvalue123 = (sel.options[sel.selectedIndex].text);
    alert(optionvalue123);       
} 

后面的JS函数正在调用的按钮...

<button name="leads" id="leads" class="btn btn-xs btn-danger" onclick="user_leads('passing some parameters for ajax'); "> Assign </button>

function user_leads('some_parameters to call in ajax') {

    var assign_user = MyApp.optionvalue2;
    alert(assign_user);  /*i get value in alert box...*/

    var assign_user123 = MyApp.optionvalue123;
    alert(assign_user123);  /*i get value in alert box...*/

    Didn't work /*$('#userName').html(assign_user123);*/

    Didn't work /* $('#userName').text($('#user').text(assign_user123));*/

    Didn't work /* $('#userName').text(assign_user123);*/

    Didn't work //document.getElementById("userName").innerHTML = assign_user123;

    $.ajax({
        /*Some Ajax function to post data*/
    });
}

在控制台中,没有错误或警告...

2 个答案:

答案 0 :(得分:0)

document.querySelector('#someOtherID').textContent = document.getElementById('some_other_ID').value;

首先,JS历来没有可分配的属性(原始值除外)。而您想要的方法是text()

尝试

$('#someOtherID').text("new value");

(使用jQuery的CSS选择器快捷方式。)

对于要分配的值

  

document.getElementById('some_other_ID')。value

除非#some_other_ID是输入元素(具有value属性),否则您将需要再次使用text()(不带参数,它将返回当前文本内容):

 $('#someOtherID').text($('#some_other_ID').text());

答案 1 :(得分:0)

您可以像编辑td的innerHTML一样

$('#userName').html(assign_user123);