简体   繁体   English

替换跨度元素旁边的输入值

[英]Replace an input value next to span element

I have to this input: 我必须输入以下内容:

<input type="text" id="my_input" />

After a user enters anything in the input I have to append this next to the span. 用户在输入中输入任何内容后,我必须将此内容附加到跨度旁边。

<p id="patient_provider" >
  <span>
    Name
  </span>
  Sam
</p>

The code I used is(It should be something like below): 我使用的代码是(应该如下所示):

  $("#patient_provider").html($('#patient_provider').children()[0]+$('#my_input').val());

But this is not working. 但这是行不通的。

It is showing something like: 它显示如下:

[object HTMLSpanElement] Sam

Also please note : 另外请注意:

There are some css implemented on the span directly and I can not add another span 直接在范围上实现了一些CSS,我无法添加另一个范围

$('#patient_provider').children()[0] is an element and is converted to a [object HTMLSpanElement] string $('#patient_provider').children()[0]是一个元素,并转换为[object HTMLSpanElement]字符串

The right is: 右边是:

 $("#patient_provider").html($('#patient_provider').children()[0].outerHTML+$('#my_input').val());

If you have the ability to change the markup, I would do so. 如果您有能力更改标记,我会这样做。 Something like so - wrapping the place where the name should appear in an element with a useful class. 像这样-用有用的类将名称应出现在元素中的位置包裹起来。 In this case, I went with a span with class name : 在这种情况下,我使用了一个类namespan

<input type="text" name="name" id="my_input">
<p id="patient_provider" >
  <span>Name</span>
  <span class="name">Sam</span>
</p>

Then, your javascript could be improved by doing something like so: 然后,可以通过执行以下操作来改进您的JavaScript:

// No-conflict-mode-safe document ready
jQuery(function($) {
    // Find the right input based on the name, and bind to keyup
    $('input[name="name"]).on('keyup', function() {
        // Put the value of the input into the span.name element
        $('#patient_provider .name').text($(this).val());
    );
});

try this, 尝试这个,

HTML 的HTML

<input type="text" id="my_input" />

<p id="patient_provider" >
  <span>
    Name:
  </span>
  <span class="patient_name">
      Sam
  </span>
</p>

JS JS

 var patientName = $(".patient_name").text();
 var editedName = false;

 $('#my_input').bind('keydown', function(){
    if(editedName == false){
        $(".patient_name").html($(this).val());
         patientName = $(".patient_name").text();
        editedName = true;
    }
 });

 $('#my_input').bind('keyup', function(){
    if(editedName == true){
            $(".patient_name").text(patientName + $(this).val());
    }
 });

JS Fiddle JS小提琴

https://jsfiddle.net/guruling/8afzf4dv/

The way you have it now, that code is only going to run once. 您现在拥有的方式,该代码将只运行一次。 You need to wrap it in an event listener so that it runs whenever a users changes the input or when they click an enter button. 您需要将其包装在事件侦听器中,以便每当用户更改输入或单击Enter按钮时它便会运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM